如何解决VBA中的运行时错误3075?

问题描述 投票:0回答:1

我在运行这段代码时遇到了问题。在查询表达式中,它给了我语法错误(缺少运算符)。

Function SearchCriteria()

Dim class,StateProvince,strAcademicYear As As String 
Dim task, strCriteria As String 

If isNull(Forms!frmStudentList!cboClass) Then
   Class = "[Class] LIKE '*' "
Else
   Class = [Class] = " & Forms!frmStudentList!cboClass
End If
If isNull(Forms!frmStudentList!cboStateProvince) Then
   StateProvince = "[StateProvince] LIKE '*' "
Else
   StateProvince = [StateProvince] = " & 
Forms!frmStudentList!cboStateProvince
End If
If isNull(Forms!frmStudentList!cboAcademicYear) Then
   StrAcademicYear = "[AcademicYear] LIKE '*' "
Else
   StrAcademicYear = [AcademicYear] = '" & 

Forms!frmStudentList!cboAcademicYear & "'"
End If
strCriteria = Class & "AND" & StateProvince & "AND" & StrAcademicYear
task = "SELECT * FROM QryStudentSearch WHERE & Criteria
Forms!frmStudentList.RecordSource = task
Forms!frmStudentList.Requery

End Function 
access-vba
1个回答
0
投票

这段代码有不少问题。

  • 首先,你的大多数变量并没有明确地声明是一个类型,所以默认为是 Variant.
  • 其次,Class在Access中是一个保留字,可能会给你带来问题。
  • 如果一个控件没有做出选择,那么你使用的是 LIKE '*' 来选择数据。没有必要这样做,因为不应用过滤器意味着无论如何都会返回所有记录。
  • 由于它不返回一个值,你可以把它创建成一个叫做 Sub 而非 Function.
  • 主要的问题是你如何将不同的部分连在一起。

我会将代码重写为

Sub sSearch()
    Dim strSearch As String
    If Not IsNull(Forms!frmStudentList!cboClass) Then
        strSearch = strSearch & " AND [Class]='" & Forms!frmStudentList!cboClass & "' "
    End If
    If Not IsNull(Forms!frmStudentList!cboStateProvince) Then
        strSearch = strSearch & " AND [StateProvince]='" & Forms!frmStudentList!cboStateProvince & "' "
    End If
    If Not IsNull(Forms!frmStudentList!cboAcademicYear) Then
        strSearch = strSearch & " AND [AcademicYear]='" & Forms!frmStudentList!cboAcademicYear & "' "
    End If
    If Left(strSearch, 4) = " AND" Then
        strSearch = "WHERE " & Mid(strSearch, 6)
    End If
    strSearch = "SELECT * FROM qryStudentSearch " & strSearch
    Forms!frmStudentList.RecordSource = strSearch
    Forms!frmStudentList.Requery
End Sub

在每一种情况下,我都假设每个组合框的约束列是文本, 因此需要在数据周围使用单引号。如果绑定列是数字,那么单引号可以去掉。

请注意。

© www.soinside.com 2019 - 2024. All rights reserved.