Query con più criteri di filtro dati , con clausole AND e OR

Anonimo
2016-07-21T07:54:46+00:00

Buongiorno a tutti, ho creato la query sottostante  per poter esportare in Excel dei dati filtrati tramite textbox e combobox su maschera, solo che mi esporta  i dati filtrati solo valutando il criterio della 1^ txtbox chiamata txtPozzoTipo e non valutando gli altri parametri di filtro degli altri controlli sulla frmOrePozzo.

Chiedo il vostro aiuto per poter modificare la query in argomento con la possibilità di valutare anche gli altri criteri di filtro attivati.

SELECT tblTurniIrrigazione.PozzoTipo, tblTurniIrrigazione.Del, tblTurniIrrigazione.Tempo, tblSoci.CognomeNome

FROM tblSoci INNER JOIN tblTurniIrrigazione ON tblSoci.ID_Socio = tblTurniIrrigazione.ID_Socio

WHERE (((tblTurniIrrigazione.PozzoTipo) Like Nz(Forms!frmOrePozzo!txtPozzoTipo,"*"))) Or (((tblTurniIrrigazione.Del) Like Nz(Forms!frmOrePozzo,"*"))) Or (((tblTurniIrrigazione.Tempo) Between Forms!frmOrePozzo!txtDal And Forms!frmOrePozzo!txtAl)) Or (((tblSoci.CognomeNome) Like Nz(Forms!frmOrePozzo!cboCognomeNome,"*")))

ORDER BY tblSoci.CognomeNome;

Spero di essere stato chiaro, il Db è al seguente link: http://www.maurogsc.eu/varie/ProvaNichi.zip e la query la lancio dal pulsante con l'immagine di Excel.

Ciao Nicola.

Microsoft 365 e Office | Access | Per la casa | Windows

Domanda bloccata. Questa domanda è stata eseguita dalla community del supporto tecnico Microsoft. È possibile votare se è utile, ma non è possibile aggiungere commenti o risposte o seguire la domanda.

0 commenti Nessun commento
Risposta accettata dall'autore della domanda
Anonimo
2016-07-22T13:34:00+00:00

ciao Nicola,

spero di avere letto tutto ed ho visto  il post sulla sezione di xls .

qui mi sembra si  discutesse del filtro che hai  trattato con Mimmo:

http://answers.microsoft.com/it-it/office/forum/office\_2013\_release-access/query-somma-ore-e-minuti-e-query-che-filtra-i-dati/455db579-b3cb-4e6d-8c10-238375606ebf

secondo me potrebbe esseree il caso di sfruttare il filtro applicato alla form per passarlo al metodo queryTables per popolare un  file di excel, anziché creare un altra query.

Da access direi di estrarre tutte le colonne che ti servono senza manipolare post il file di  xls creato.

lo stesso per l'aggiunta della funzione somma delle ore.

Il filtro  diventa così :

Private Sub cmdFilter_Click()

Dim strFilter As String

strFilter = ""

Const concat As String = " and "

If Nz(Me.txtPozzoTipo) <> "" Then strFilter = strFilter & "PozzoTipo=" & Me.txtPozzoTipo & concat

If Nz(Me.txtDal) <> "" Then strFilter = strFilter & "del between " & CLng(Me.txtDal) & concat & CLng(Me.txtAl) & concat

If Nz(Me.cboAnno) <> "" Then strFilter = strFilter & "year(del)='" & Me.cboAnno & "'" & concat

If Nz(Me.cboCognomeNome) <> "" Then strFilter = strFilter & Me.cboCognomeNome & concat

If Len(strFilter) > 0 Then

    strFilter = Left$(strFilter, Len(strFilter) - Len(concat))

    Me.Filter = strFilter

    Me.FilterOn = True

Else

    Me.Filter = ""

    Me.FilterOn = False

End If

End Sub

il  codice di  esportazione su xls così :

Private Sub cmdEsportaExcel_Click()

Dim strSql As String

strSql = "SELECT TblPozzo.Tipo, TblPozzo.Descrizione, tblTurniIrrigazione.Del, CDate(CDbl([tempo])) as tempoOra, tblSoci.CognomeNome" & _

         " FROM tblSoci INNER JOIN (TblPozzo INNER JOIN tblTurniIrrigazione ON TblPozzo.Tipo = tblTurniIrrigazione.ID_Socio) ON tblSoci.ID_Socio = tblTurniIrrigazione.ID_Socio "

If Len(Me.Filter) <> 0 Then

    strSql = strSql & " where " & Me.Filter

End If

' Debug.Print strSql

export2XLs2 strSql

End Sub

e questo il  modulo per esportare su xls :

Option Compare Database

Option Explicit

Public Sub export2XLs2(ByVal strSql As String)

Dim xlApp      As Object

Dim wbk        As Object 'as Workbook

Dim wsh        As Object 'as Worksheet

Dim LastRow    As Long

Dim dbp        As Access.CurrentProject

Dim bool       As Boolean

Dim xlQry      As Object

 Const cstrXlClass = "Excel.Application"

 Const cstrFullName = "c:\prova\nicola.xlsx"

 If fileExists(cstrFullName) Then Kill cstrFullName

 Const cstrCnn = "OLEDB;Provider=Microsoft.ACE.OLEDB.12.0" _

              & ";Data Source=" & cstrFullName _

              & ";Mode=Read;"

Dim blnNotRunning      As Boolean

Dim strCnn             As String

With Application

     Set dbp = .CurrentProject

End With

strCnn = Replace(cstrCnn, cstrFullName, dbp.FullName)

blnNotRunning = getXlSinstance(xlApp, False, cstrXlClass)

With xlApp

    If blnNotRunning Then

       ' .Visible = True

       .ScreenUpdating = False

    End If

End With

If fileExists(cstrFullName) Then

    Set wbk = xlApp.Workbooks.Open(cstrFullName)

Else

    Set wbk = xlApp.Workbooks.Add

End If

Set wsh = wbk.Worksheets.Item(1)

LastRow = wsh.range("A1").end(-4121).Row '  xlDown

If LastRow = wsh.cells(wsh.cells.Rows.Count, 1).end(-4121).Row Then

    LastRow = 1

    bool = Not bool

End If

 With wsh

    Set xlQry = .QueryTables.Add(Connection:=strCnn _

                                     , Destination:=.range("A" & LastRow))

End With

With xlQry

     .CommandType = 2      ' 2 è la costante per xlCmdSql

     .CommandText = strSql

     .AdjustColumnWidth = bool

     .FieldNames = bool

     .Refresh

     .Delete

End With

With xlApp

         .displayAlerts = False

        .ScreenUpdating = True

        .Calculation = -4105 'xlAutomatic

        LastRow = LastWbkRow(wsh)

        With wsh

            .cells(2 + LastRow, 4).Value = "=SUM(d2:d" & LTrim(Str(LastRow)) & ")"

            .cells(2 + LastRow, 4).numberFormat = "hh:mm:ss"

            .range("d2:d" & LTrim(Str(LastRow))).numberFormat = "hh:mm:ss"

        End With

         wbk.SaveAs FileName:=cstrFullName

         wbk.Close SaveChanges:=True _

              , FileName:=cstrFullName

        .displayAlerts = True

End With

    MsgBox "Salvato ed esportato", vbInformation, "Avviso"

exitErrorHandler:

    Set wsh = Nothing

    Set wbk = Nothing

    xlApp.Quit

    Set xlApp = Nothing

    Exit Sub

errorHandler:

    With Err

            MsgBox "ERR#" & CStr(.Number) _

                & vbNewLine & .Description _

                , vbOKOnly Or vbCritical

     End With

     Resume exitErrorHandler

End Sub

' funzione LastWbkRow Norman David Jones

Public Function LastWbkRow(SH As Object, Optional Rng As Object, _

                        Optional minRow As Long = 1)

    If Rng Is Nothing Then

        Set Rng = SH.cells

    End If

    On Error Resume Next

    LastWbkRow = Rng.Find(What:="*", After:=Rng.cells(1), _

                       Lookat:=2, _

                       LookIn:=-4123, _

                       SearchOrder:=1, _

                       SearchDirection:=2, _

                       MatchCase:=0).Row

    On Error GoTo 0

    If LastWbkRow < minRow Then

        LastWbkRow = minRow

    End If

End Function

Private Function getXlSinstance(xlApp As Object _

                                , isXlsRunning As Boolean _

                                , strClass As String) As Boolean

    Err.Clear

    If isXlsRunning Then

        On Error Resume Next

        Set xlApp = GetObject(, strClass)

    End If

    If xlApp Is Nothing Then

        Set xlApp = CreateObject(strClass)

    End If

    If Err <> 0 Then

        MsgBox "Qualcosa non va controlla questo l'errore:" & Err.Description, _

                vbCritical, "Attenzione!!!"

        getXlSinstance = False

    Else

        getXlSinstance = True

    End If

End Function

Private Function fileExists(strFullPath As String) As Boolean

    On Error Resume Next

    fileExists = ((GetAttr(strFullPath) And vbDirectory) = 0)

End Function

Private Function folderExists(strPath As String) As Boolean

    On Error Resume Next

    folderExists = ((GetAttr(strPath) And vbDirectory) = vbDirectory)

End Function

post esportazione controlla la cartella c:\prova trovi il file con l'esportazione filtrata il file si chiama nicola.xlsx

questo il tuo database modificato.

Facci  sapere.

Ciao,Sandro.

La risposta è stata utile?

0 commenti Nessun commento
Risposta accettata dall'autore della domanda
Anonimo
2016-07-22T11:18:51+00:00

Prova a sostituire il tuo codice con questo:

Private Sub cmdFilter_Click()

    Dim wFiltro As String

    wFiltro = ""

    If Nz(Me.txtDal) And (Me.txtAl) <> "" Then

       wFiltro = "[Del] between #" & txtDal & "# AND #" & txtAl & "#"

    End If

    If Nz(Me.cboAnno) <> "" Then

       If wFiltro = "" Then

          wFiltro = "year([Del])='" & Me.cboAnno & "'"

       Else

          wFiltro = wFiltro & " And year([Del])='" & Me.cboAnno & "'"

       End If

    End If

    If Not IsNull(Me.txtPozzoTipo) Then

       If wFiltro = "" Then

          wFiltro = "PozzoTipo = " & Me.txtPozzoTipo

       Else

          wFiltro = wFiltro & " And PozzoTipo = " & Me.txtPozzoTipo

       End If

    End If

      If Not IsNull(Me.cboCognomeNome) Then

        If wFiltro = "" Then

           wFiltro = "CognomeNome LIKE '*" & Me.cboCognomeNome & "*'"

        Else

           wFiltro = wFiltro & " And CognomeNome Like '*" & Me.cboCognomeNome & "*'"

        End If

     End If

    'If Not IsNull(fltDataNascita) Then

       'If wFiltro = "" Then

          'wFiltro = "Pe_DataNascita = #" & Format(Me.fltDataNascita, "yyyy/mm/dd") & "#"

       'Else

          'wFiltro = wFiltro & " And Pe_DataNascita = #" & Format(Me.fltDataNascita, "yyyy/mm/dd") & "#"

       'End If

    'End If

    Me.Filter = wFiltro

    Me.FilterOn = True

Me.Refresh

End Sub

Ciao Mimmo

La risposta è stata utile?

0 commenti Nessun commento

34 risposte aggiuntive

Ordina per: Più utili
  1. Anonimo
    2016-08-12T12:32:18+00:00

    Ciao Sandro, provando e riprovando come un forsennato ho notato che quando compatto e ripristino il DB, noto un leggero sfarfallio del monitor per pochi secondi, non è per caso che l'errore si verifica perché il mio sistema operativo è a 64 bit ed ho office 2013 a 64 bit?

    Ciao Nicola, fammi sapere Sandro, devo uscire prima possibile da questo problema, sono bloccato.

    La risposta è stata utile?

    0 commenti Nessun commento
  2. Anonimo
    2016-08-12T10:40:34+00:00

    Ciao Sandro, grazie come sempre per il tuo gentile intervento, è da ieri che provo  e riprovo sempre sui tuoi consigli ma, purtroppo (sto impazzendo non riesco a capire coem nel DB Origionale e completo non va) ho sempre lo stesso problema di ieri sul ME.REFRESH che si colora di giallo.

    Penso proprio che dovrei inviarti il db originale (altrimenti non ne esco fuori da questo problema, io ce la sto mettendo tutta ma non riesco a risolvere l'enigma).

    **Lo so che non è questo lo scopo della community,**ma credo che sia necessario e risolutivo pubblicarti personalmente il mio DB originale, sul quale dopo aver apportato tutte le tue variazioni di codice consigliate si verifica il problema.

    Se posso e se tu lo vuoi potresti in dicarmi la tua e-mail ecc.

    Resto in attesa e mi scuso con gli altri utenti per questo, non posso pubblicare il DB integrale poichè contiene dei dati sensibili.

    Ciao Nicola.

    La risposta è stata utile?

    0 commenti Nessun commento
  3. Anonimo
    2016-08-11T15:32:50+00:00

    ciao Nicola,

    nessun me.refresh, in questo caso refresh è  un metodo membro di excel.querytable.

    Per l'esportazione, c'è un errore di join nella query ed il controllo del recordsetClone va fatto ad inizio routine come detto nel post precedente.

    Private Sub cmdEsportaExcel_Click()

    If Me.RecordsetClone.RecordCount = 0 Then

         VBA.MsgBox "Nessun records filtrato!", vbCritical, "Warning"

         Exit Sub

     End If

    Dim strSql   As String

    Dim strFilter As String

    strFilter = Me.Filter

    'strSql = "SELECT TblPozzo.Tipo, TblPozzo.Descrizione, tblTurniIrrigazione.Del, CDate(CDbl([tempo])) as tempoOra, tblSoci.CognomeNome" & _

    '          " FROM tblSoci INNER JOIN (TblPozzo INNER JOIN tblTurniIrrigazione ON TblPozzo.Tipo = tblTurniIrrigazione.ID_Socio) ON tblSoci.ID_Socio = tblTurniIrrigazione.ID_Socio "

    strSql = "SELECT TblPozzo.Tipo, TblPozzo.Descrizione, tblTurniIrrigazione.Del, CDate(CDbl([tempo])) as tempoOra, tblSoci.CognomeNome" & _

                      " FROM (tblSoci INNER JOIN tblTurniIrrigazione ON tblSoci.ID_Socio = tblTurniIrrigazione.ID_Socio) INNER JOIN TblPozzo ON tblTurniIrrigazione.PozzoTipo = TblPozzo.Tipo "

    If Len(strFilter) <> 0 Then

         If InStr(1, strFilter, "id_socio") > 0 Then strFilter = Replace(strFilter, "id_socio", "tblsoci.id_socio")

         strSql = strSql & " where " & strFilter

     End If

    export2XLs2 strSql

    End Sub

    per il resto non ho individuato errori come vedi delle immagini sotto.

    segui scrupolosamente i passi.

    1)apri il db

    2)modifica la routine fai un copia incolla di quanti trovi qui sopra.

    3)salva tutto

    1. chiudi il db

    5)riapri e filtra ed esporta.

    ciao, Sandro

    ![](http://fud.community.services.support.microsoft.com/Fud/FileDownloadHandler.ashx?fid=76dd7cb0-e265-4b80-a372-743f3a572036)

    ![](http://fud.community.services.support.microsoft.com/Fud/FileDownloadHandler.ashx?fid=e275e614-d666-408d-b016-37c839751b20)

    La risposta è stata utile?

    0 commenti Nessun commento