VBA query build

TooManyReports

Registered User.
Local time
Today, 09:32
Joined
Aug 13, 2010
Messages
43
I got this script that I am trying to modify to add more restrictions to a query.
Code:
Private Sub cmdOpenQuery_Click()
On Error GoTo Err_cmdOpenQuery_Click
    Dim MyDB As DAO.Database
    Dim qdef As DAO.QueryDef
    Dim i As Integer
    Dim strSQL As String
    Dim strWhere As String
    Dim strIN As String
    Dim flgSelectAll As Boolean
    Dim varItem As Variant
    
    Set MyDB = CurrentDb()
    
    strSQL = "SELECT * FROM [REGIONS]"
    
    'Build the IN string by looping through the listbox
    For i = 0 To lst2Region.ListCount - 1
        If lst2Region.Selected(i) Then
            If lst2Region.Column(0, i) = "All" Then
                flgSelectAll = True
            End If
            strIN = strIN & lst2Region.Column(0, i) & ","
        End If
     Next i
     
    'Create the WHERE string, and strip off the last comma of the IN string
    strWhere = " WHERE [REGION] in " & "(" & Left(strIN, Len(strIN) - 1) & ")"
    
    'If "All" was selected in the listbox, don't add the WHERE condition
    If Not flgSelectAll Then
        strSQL = strSQL & strWhere
    End If
    
    MyDB.QueryDefs.Delete "qryREGIONS"
    Set qdef = MyDB.CreateQueryDef("qryREGIONS", strSQL)
    
    'Open the query, built using the IN clause to set the criteria
    'DoCmd.OpenQuery "qryREGIONS", acViewNormal
    
    'Clear listbox selection after running query
    For Each varItem In Me.lst2Region.ItemsSelected
        Me.lst2Region.Selected(varItem) = False
    Next varItem
    
    
Exit_cmdOpenQuery_Click:
    Exit Sub
    
Err_cmdOpenQuery_Click:

   If Err.Number = 5 Then
        MsgBox "You must make a selection(s) from the list", , "Selection Required !"
        Resume Exit_cmdOpenQuery_Click
    Else
    'Write out the error and exit the sub
        MsgBox Err.Description
        Resume Exit_cmdOpenQuery_Click
    End If

End Sub

What i am trying to do is build a query that can have 2 fields updated.

For example I have this is a multi-select list box:

REGION SUBREGION
2-------------- 0
2-------------- 5
3-------------- 0
4-------------- 0
4-------------- 3

Currently this VBA builds a sql script that says
Code:
select * from [REGIONS] WHERE in (2,3)

I need a way to build a sql script that says
Code:
SELECT REGIONS.[Region], REGIONS.[SubRegion]
FROM REGIONS
WHERE (((REGIONS.[Region]) In (2)) AND ((REGIONS.[SubRegion]) In (0,5))) OR (((REGIONS.[Region]) In (3)) AND ((REGIONS.[SubRegion]) In (0)));

Thanks for any help in advance!
 
Last edited:
Sorry, but that is not going to help me. I could use a sample of the coding. That site did not allow for multiselections with different requirements.
 

Users who are viewing this thread

Back
Top Bottom