Run-time error 3167 and Run-time error 3012

后端 未结 1 427
故里飘歌
故里飘歌 2020-12-22 07:17

I have a question regarding the code below which creates a new query based on combobox selections or a textbox entry on an Access form.

Sometimes when I run the que

相关标签:
1条回答
  • 2020-12-22 08:08

    The runtime errors might be fixed by adding DB.QueryDefs.Refresh after adding or deleting a querydef.

    Dim DB As Database
    
    Set DB = CurrentDb
    DB.QueryDefs.Delete "NewQuery"
    DB.QueryDefs.Refresh
    
    Set qdf = DB.CreateQueryDef("NewQuery", sqlquery)
    DB.QueryDefs.Refresh
    DoCmd.OpenQuery "NewQuery"
    

    There are some other problems with your code.

    You should give your form controls meaningful names instead of e.g. ComboBox4. This will help readability a lot.

    Your construction of ComboBox_condition is overly complex. The most elegant solution to avoid all these doubled conditions is:

    Always add them with AND, including the first one:

    If ComboBox0 <> "" Then
        ComboBox_condition = ComboBox_condition + " AND TABLE.PayGroupRegionCode = '" & ComboBox0 & "'"
    End If
    ' ...
    If ComboBox12 <> "" Then
        ComboBox_condition = ComboBox_condition + " AND TABLE.JobCode = '" & ComboBox12 & "'"
    End If
    ' ...
    

    and then when you build the final statement, add a dummy WHERE condition that is always True, so the WHERE clause is always valid:

    sqlquery = "SELECT * FROM TABLE WHERE 1=1 " & ComboBox_condition
    

    Even the check If ComboBox_condition <> "" can be omitted.

    0 讨论(0)
提交回复
热议问题