简体   繁体   中英

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

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 ='.

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.

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

您需要引用字符串

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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