如何在查询表中循环访问sql代码

时间:2013-08-21 18:18:11

标签: sql excel vba import

我想根据其中一列中的值将excel电子表格中的某些列插入到sql中,我编写了sql代码,但是当我循环遍历代码时,它会不断添加新的querytbale。有没有办法将值插入sql刷新带有新值的查询表并将其插入到同一个sql表中?

sqlString = "Insert into table(fields) select '" & ws1.Cells(row, col) & "','" & ws1.Cells(row, co2) & "','" & ws1.Cells(row, col3) & "','" & ws1.Cells(row, col4) & "','" & ws1.Cells(row, col5) & "','" & ws1.Cells(row, col6) & "'"


Set destination = ws2.Range("A1")
Set pleasework = ws2.QueryTables.Add(conString, destination, sqlString)

sqlString = "Insert into table(fields) select '" & ws1.Cells(row, col) & "','" & ws1.Cells(row, co2) & "','" & ws1.Cells(row, col3) & "','" & ws1.Cells(row, col4) & "','" & ws1.Cells(row, col5) & "','" & ws1.Cells(row, col6) & "'"

Do

With pleasework

        row = row + 1
        .CommandText = sqlString
        .Refresh
        count = count + 1

End With
Loop While count < 5

1 个答案:

答案 0 :(得分:0)

您可以放弃您的代码并尝试以下内容:

query = INSERT INTO [ODBC;DRIVER=SQL Server;SERVER=MY_COMPUTER\SQLEXPRESS;Trusted_Connection=Yes;DATABASE=MY_DATABASE].[tbMYTALBE] ([FIELD1], [FIELD2], [FIELD3]) SELECT t.FIELD1,  t.FIELD2, t.FIELD3 FROM [MY_SHEET$A1:D200] t
Call recordSet.Open(query, connection)

如果需要,我可以添加完整的代码