Com crear un quadre de diàleg per Filtrar, buscar i recuperar els registres d'una taula en un formulari Access, segons diferents critèris, mitjantçant codi VBA

Per construir un quadre de diàleg que ens permeti filtrar, buscar i recuperar registres d'una taula d'Access utilitzant diferents critèris de búsqueda, podem fer servir el següent exemple:

El codi situat en l'event "Al hacer clic" del botó Acceptar permet construir una sentència SQL que filtra els registres que compleixen les condicions que hem establert en aquest quadre de diàleg de búsqueda i els mostra en el formulari que té al seu darrera.
 Private Sub cmdAcceptarBuscarClients_Click()
Dim registres As ADODB.Recordset
Set registres = New ADODB.Recordset
Dim strSQL As String
Dim where As Variant
where = Null
If Not IsNull(txtRaoSocial.Value) Then
where = where & (" [NOFCLI] LIKE '" & Me!txtRaoSocial & "'")
End If
If Not IsNull(txtDomicili.Value) Then
    If Len(where) > 0 Then
    where = where & (" OR [DOMCLI] LIKE '" & Me!txtDomicili & "'")
    Else
    where = where & (" [DOMCLI] LIKE '" & Me!txtDomicili & "'")
    End If
End If
If Not IsNull(txtPoblacio.Value) Then
    If Len(where) > 0 Then
    where = where & (" OR [POBCLI] LIKE '" & Me!txtPoblacio & "'")
    Else
    where = where & (" [POBCLI] LIKE '" & Me!txtPoblacio & "'")
    End If
End If
If Not IsNull(txtCodiPostal.Value) Then
    If Len(where) > 0 Then
    where = where & (" OR [CPOCLI] LIKE '" & Me!txtCodiPostal & "'")
    Else
    where = where & (" [CPOCLI] LIKE '" & Me!txtCodiPostal & "'")
    End If
End If
If Not IsNull(txtProvincia.Value) Then
    If Len(where) > 0 Then
    where = where & (" OR [PROCLI] LIKE '" & Me!txtProvincia & "'")
    Else
    where = where & (" [PROCLI] LIKE '" & Me!txtProvincia & "'")
    End If
End If
If Not IsNull(txtNIF.Value) Then
    If Len(where) > 0 Then
    where = where & (" OR [NIFCLI] LIKE '" & Me!txtNIF & "'")
    Else
    where = where & (" [NIFCLI] LIKE '" & Me!txtNIF & "'")
    End If
End If
DoCmd.Close acForm, "frmBuscarClients"
registres.ActiveConnection = CurrentProject.Connection
registres.Source = "SELECT * FROM tblClients WHERE " & where & ";"
Forms!frmClientsContinuu.RecordSource = registres.Source
End Sub

Comentaris

Entrades populars