查询表达式'PopID ='中的VBA语法错误(缺少运算符)

时间:2013-08-13 13:18:44

标签: sql excel vba ms-access

以下代码在尝试运行时会抛出错误,我认为我已经设法实际连接到数据库并且我选择了一个单元格,因此不确定缺少什么。

错误:

  

查询表达式'PopID ='中的语法错误(缺少运算符)。

理想情况下,我希望能够列出四个单元格,每次运行宏时会在访问权限中附加四列

Const TARGET_DB = "testdb.accdb"

Sub AlterOneRecord() 'not working yet

   Dim cnn As ADODB.Connection
   Dim rst As ADODB.Recordset
   Dim fld As ADODB.Field
   Dim MyConn
   Dim lngRow As Long
   Dim lngID As String
   Dim j As Long
   Dim sSQL As String

                   'determine the ID of the current record and define the SQL statement
                   lngRow = ActiveCell.Row
                   lngID = Cells(lngRow, 1).Value

   sSQL = "SELECT * FROM tblPopulation WHERE PopID = " & lngID

   Set cnn = New ADODB.Connection
   MyConn = ThisWorkbook.path & Application.PathSeparator & TARGET_DB

   With cnn
     .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;"
     .Open MyConn
   End With

   Set rst = New ADODB.Recordset
   rst.CursorLocation = adUseServer
   rst.Open Source:=sSQL, _
            ActiveConnection:=cnn, _
            CursorType:=adOpenKeyset, _
            LockType:=adLockOptimistic

   'Load contents of modified record from Excel to Access.
   'do not load the ID again.
   For j = 2 To 7
      rst(Cells(1, j).Value) = Cells(lngRow, j).Value
   Next j
   rst.Update

   ' Close the connection
   rst.Close
   cnn.Close
   Set rst = Nothing
   Set cnn = Nothing
End Sub

我觉得奇怪的是他们都是M $产品,这些产品没有很好的记录或真的很容易执行。也许我会以错误的方式解决这个问题。

我怎么能让它包含单元格A1和B2呢?

1 个答案:

答案 0 :(得分:3)

你需要引用字符串

sSQL = "SELECT * FROM tblPopulation WHERE PopID = '" & lngID & "'"