如何使用单元格对象作为条件来创建 SQL 查询字符串?

How to create a SQL query string using a cell object as a criteria?

代码如下:

If Total_rows_NMRDTRSummary > 1 Then
Dim objConnection As Variant
Dim objRecordset As Variant
Dim connectionString As String
        Const adOpenStatic = 3
        Const adLockOptimistic = 3
        Const adCmdText = &H1

        Set objConnection = CreateObject("ADODB.Connection")
        Set objRecordset = CreateObject("ADODB.Recordset")

        connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Sun-Lap\Desktop\Payroll Computations (Template).xlsm; Extended Properties=""Excel 8.0; HDR=YES"";"
        objConnection.Open connectionString

    For i = 2 To Total_rows_NMRDTRSummary
        objRecordset.Open "Select * FROM [N-MR Data$] WHERE Person = " & ThisWorkbook.Worksheets("N-MR DTR Summary").Cells(i, 1) & " AND Date = " & ThisWorkbook.Worksheets("N-MR DTR Summary").Cells(i, 2), objConnection, adOpenStatic, adLockOptimistic, adCmdText

        Do Until objRecordset.EOF
            Debug.Print objRecordset.Fields.Item("Date"), _
                objRecordset.Fields.Item("Person")
            objRecordset.MoveNext
        Loop
    Next i
End If

问题出在 objRecordset.Open "Select * FROM [N-MR Data$] WHERE Person = " & ThisWorkbook.Worksheets("N-MR DTR Summary").Cells(i, 1) & " AND Date = " & ThisWorkbook.Worksheets("N-MR DTR Summary").Cells(i, 2), objConnection, adOpenStatic, adLockOptimistic, adCmdText

中的 SQL 字符串

如果我对字符串进行硬编码,则字符串有效,例如:objRecordset.Open "Select * FROM [N-MR Data$] WHERE Person = 'JOHN'"

但是以一种我可以加入循环的方式来做,它会出错:objRecordset.Open "Select * FROM [N-MR Data$] WHERE Person = " & ThisWorkbook.Worksheets("N-MR DTR Summary").Cells(i,1)

错误提示:

我认为在 VBA 中连接字符串的常用方式在 SQL 查询字符串中没有遵循?如何以我可以在查询中提供循环的方式正确地做到这一点?

您似乎忘记了参数的单引号

Person = '" & ThisWorkbook.Worksheets("N-MR DTR Summary").Cells(i, 1) & "' AND...

对于日期参数你应该做同样的事情