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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18210228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:43:46  来源:igfitidea点击:

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

sqlexcelvbams-access

提问by user2341069

The following code throws an error when trying to run it, I presume I've managed to actually connect to the database and I have a cell selected so not sure what's missing.

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

ERROR:

错误:

Syntax error (missing operator) in query expression 'PopID ='.

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

Ideally I would like to be able to list four cells that would go into four columns in access appending each time the macro is ran

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

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

I find it strange with them both being M$ products that this is not well documented or really really easy to perform. Maybe I'm going about it in the wrong way.

我觉得奇怪的是,它们都是 M$ 产品,这没有很好的记录或真的很容易执行。也许我以错误的方式去做这件事。

How could I make it contain cells A1 and B2 for example?

例如,我怎样才能让它包含单元格 A1 和 B2?

回答by juergen d

You need to quote strings

你需要引用字符串

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