VBA宏:无法在sql insert查询语句的循环中重置记录集(错误:运行时错误 - 自动化错误和未指定的错误)

时间:2016-01-11 13:36:01

标签: excel-vba automation runtime-error vba excel

我正在尝试减少将值插入数据库的手动操作。

问题:我希望从Excel文档中获取值行,并且在每次迭代中,我希望将行值插入到数据库中。 for循环从Excel工作表中获取数据,但是当我尝试执行查询时,只有第一个循环正在执行,之后会导致错误。

  

错误:运行时错误 - 自动化错误 - 未指定错误。

我相信结果集是问题所在,但我关闭它,我无法为下一个可执行插入查询刷新它。

如何成功运行此循环,将多行Excel数据插入数据库。

源代码:

{Sub cals()
Dim col1_autog As Long
Dim col2_categorizing As String
Dim col3_stamp As String
Dim col4_defaultB As String
Dim col5_winnumber As String
Dim col6_datetimeval As String
Dim col6_d1 As String
Dim col6_d2 As String
Dim col7_state As String
Dim col8_default1 As Integer
Dim final_query As String
Dim count As Integer
count = 1
Dim x As Integer
Dim dbconnstr As ADODB.Connection
Set dbconnstr = New ADODB.Connection
Set objMainRecord = New ADODB.Recordset
Set objCnTD = CreateObject("ADODB.Connection")
Set objMainRecord = CreateObject("ADODB.recordset")
dbconnstr.ConnectionString = "Provider = MSDASQL;Persist Security 
Info=True;Data Source = DSNV;Initial Catalog = RDWBUSTS;
User ID ="***";Password="***""
dbconnstr.Open
x = 1
Do Until x = 4
col1_autog = Sheet6.cells(x, "I").Value
col2_categorizing = Sheet6.cells(x, "A")
Dim col3_stamp_temp1 As String
Dim col3_stamp_temp2 As String
Dim col3_stamp_temp3 As String
col3_stamp_temp1 = "TMC02.S"
col3_stamp_temp2 = ".US"
col3_stamp_temp3 = Sheet6.cells(x, "G")
col3_stamp = col3_stamp_temp1 & col3_stamp_temp2 & col3_stamp_temp3
col4_defaultB = "B"
col5_winnumber = Sheet6.cells(x, "D")
col6_d1 = Sheet6.cells(x, "E")
col6_d2 = Sheet6.cells(x, "F")
col6_datetimeval = col6_d1 & col6_d2
Dim col7_s1 As String
col7_s1 = "Dst=T&Online=T&Dtz=America/"
Dim col7_s2 As String
col7_s2 = Sheet6.cells(x, "G")
col7_state = col7_s1 & col7_s2
col8_default1 = 1
final_query = "INSERT INTO RDWBUSTS.CLOCK_TRAN_PEND_J         
(CTPJ_ID,CTPJ_TYPE,CTPJ_RDR_NAME,CTPJ_IDENT_TYPE,
CTPJ_IDENTIFIER,CTPJ_TIME,CTPJ_EXTRADATA,CLIENT_ID)
Values ( " & col1_autog & ",'" & col2_categorizing & "', 
'" & col3_stamp & "','" & col4_defaultB & "',
'" & col5_winnumber & "','" & col6_datetimeval & "',
'" & col7_state & "'," & col8_default1 & ")"
objMainRecord.Open final_query, dbconnstr
objMainRecord.Close
MsgBox "loop" & x
x = x + 1
dbconnstr.Close
End Sub}

1 个答案:

答案 0 :(得分:1)

你永远不会关闭循环。

在您的情况下,循环以:Do Until x = 4

开头

并且必须以:Loop

结束

像这样:

Do Until x = 4
    'Do stuff
Loop

您希望循环结束取决于您的逻辑。