我在Excel中有一些代码根据RTP_ID是否等于IngID来更新Access表,以下匹配并且如果它们在RTP_ID中是数字则有效:
sSQL = "SELECT * FROM Tbl_Primary WHERE RTP_ID = " & lngID
但我希望RTP_ID
可以成为字符串。
我试过了:
sSQL = "SELECT * FROM Tbl_Primary WHERE RTP_ID = '" & lngID & "'"
但这仍然无效,有什么想法吗?
因此,如果RTP_ID
为1
,那么它会起作用,但如果它是1A
则不行。
编辑 - 这是我目前的代码:
Application.ScreenUpdating = False
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim fld As ADODB.Field
Dim MyConn
Dim lngRow As Long
Dim lngID, LR, Upd
Dim strID As String
Dim j As Long
Dim sSQL As String
LR = Range("B" & Rows.Count).End(xlUp).Row
Upd = LR - 1
lngRow = 2
Do While lngRow <= LR
strID = Cells(lngRow, 2).Value
sSQL = "SELECT * FROM Tbl_Primary WHERE RTP_ID2 = " & strID
Set cnn = New ADODB.Connection
MyConn = "Provider = Microsoft.ACE.OLEDB.12.0;" & _
"Data Source =\Work\Sites\HLAA\NEW\test\HLAA 2015 NEW.mdb"
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn
End With
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open sSQL, ActiveConnection:=cnn, _
CursorType:=adOpenKeyset, LockType:=adLockOptimistic
.
With rst
.Fields("MonitorCapacity") = Cells(lngRow, 74).Value
rst.Update
End With
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
lngRow = lngRow + 1
Loop
MsgBox "You just updated " & Upd & " records"
答案 0 :(得分:1)
我会重写以下代码:
Dim cnn As Object
Dim lngRow As Long
Dim lngID As Long, LR As Long, Upd As Long
Dim strID As String
LR = ThisWorkbook.Worksheets("Sheet2").Range("B" & Rows.Count).End(xlUp).Row
Upd = LR - 1
lngRow = 2
Set cnn = CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=\Work\Sites\HLAA\NEW\test\HLAA 2015 NEW.mdb;" & _
"Persist Security Info=False;"
Do While lngRow <= LR
strID = ThisWorkbook.Worksheets("Sheet2").Cells(lngRow, 2).Value
cnn.Execute "UPDATE Tbl_Primary SET MonitorCapacity = '" & _
ThisWorkbook.Worksheets("Sheet2").Cells(lngRow, 74).Value2 & _
"' WHERE RTP_ID2 = '" & strID & "'"
lngRow = lngRow + 1
Loop
MsgBox "You just updated " & Upd & " records"
您可能需要更改工作表名称 - 当您刚刚放置Range("B" & Rows.Count)
时,它将使用当时处于活动状态的工作表,因此需要说明工作表。