繁体   English   中英

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

[英]VBA Syntax error (missing operator) in query expression 'PopID ='

以下代码在尝试运行它时引发错误,我想我已经设法成功连接到数据库,并且选择了一个单元格,因此不确定丢失了什么。

错误:

查询表达式“ 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?

您需要引用字符串

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM