将数据从excel文件(VBA)上传到Access后端时遇到问题。
我正在尝试在一笔交易中上传2条记录。使用循环即可完成。
代码的相关部分。
cnn.BeginTrans
'(some test data)
SomeNumber = 2
NewText = "new text"
For i = 0 To 1
Set cmd = New ADODB.Command
'(increase [counter] field in database)
With cmd
.ActiveConnection = cnn
.CommandType = adCmdText
.CommandText = "UPDATE [tbltest] " & _
"SET [counter] = [counter] + 1 " & _
"WHERE [counter] > ?"
.Parameters.Append .CreateParameter(, adInteger, adParamInput, , SomeNumber)
.Execute
End With
Set cmd = New ADODB.Command
'(insert new row in gap)
With cmd
.ActiveConnection = cnn
.CommandType = adCmdText
.CommandText = "INSERT INTO [tbltest] ([counter], [txtfield]) " & _
"VALUES (?, ?)"
.Parameters.Append .CreateParameter(, adInteger, adParamInput, , SomeNumber + 1)
.Parameters.Append .CreateParameter(, adVarChar, adParamInput, 50, NewText & i)
.Execute
End With
Next i
cnn.CommitTrans
tblTest开始
Counter, txtfield
1 , Sometext1
2 , Sometext2
3 , Sometext3
4 , Sometext4
预期产量
Counter, txtfield
1 , Sometext1
2 , Sometext2
5 , Sometext3
6 , Sometext4
3 , Sometext1
4 , Sometext0
但是我得到的是
Counter, txtfield
1 , Sometext1
2 , Sometext2
5 , Sometext3
6 , Sometext4
3 , Sometext1
3 , Sometext0
因此,似乎在第一循环中插入的counter
在第二循环中没有更新。
我已经使用SQL Server作为后端测试了相同的代码,并且按预期工作。
但是由于某些原因,它与Access后端的工作方式有所不同。
我是否缺少某些东西,或者使用Access作为后端无法通过这种方式完成?
编辑
行Set cmd = New ADODB.Command
应该在更新命令之前的for
循环之内,而不是外部。