错误处理仍然会引发运行时错误

时间:2016-10-06 21:37:45

标签: sql vba access-vba

我在捕获错误时遇到问题,基本上我有一个表单,用户选择几个月来打开表单,如果没有选择月份,那么IN SQL查询将抛出运行时错误WHERE条款中的MsgBox内没有任何内容。

因此,一旦发生错误,Resume Exit_Error甚至不会弹出,只会抛出运行时错误'3075'。如果我删除Exit_ErrorMsgBox,则Private Sub Report_Open(Cancel As Integer) On Error GoTo Error_handler Dim months As String months = IIf([Forms]![Select]![January].Value = True, ",1", "")& _ IIf([Forms]![Select]![February].Value = True, ",2", "") ...(And so on for each month) months = Mid(months, 2) CreateSQL = "SELECT * FROM [Table] WHERE MONTH (Date_Happened) IN (" & months & ")" Me.RecordSource = CreateSQL Exit_Error: Exit Sub Error_handler: MsgBox "Please select an appropriate date (Month/s AND Year)" Resume Exit_Error End Sub 会弹出,但之后会再次抛出运行时错误。我在尝试捕捉错误时是否在做错了什么?

{{1}}

1 个答案:

答案 0 :(得分:1)

错误是由查询IN(,1)中的空元素引起的。我使用create functions来返回我的查询字符串,以便我可以在查询设计器中测试我的查询。

错误:

enter image description here

输出:

enter image description here

代码:

Function getDateHappenQuery() As String
    Const BASE_SQL As String = "SELECT * FROM [Table] WHERE MONTH (Date_Happened) IN ( @months )"
    Dim i As Integer
    Dim s As String

    With [Forms]![Select]
        For i = 1 To 12
            If .Controls(MonthName(i)).Value Then s = s & i & ","
        Next
    End With

    s = Left(s, Len(s) - 1)

    If Len(s) Then getDateHappenQuery = Replace(BASE_SQL, "@months", s)

End Function