我是EXCEL-VBA和SQL的新手。我设法创建了marco按钮并将excel单元数据推送到SQL服务器表。但是,我有点不解: 问:如何从不同的工作表中获取excel单元格数据,然后将它们推送到SQL Server数据库中的不同表? (目前,我在一个excel文件中有3张{Customers,Test,Information})
当前工作代码:
Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sCustomerId, sFirstName, sLastName As String
With Sheets("Customers")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=TESTpc\SQLEXPRESS;Initial Catalog=ExcelSQLServerDemo;Trusted_connection=yes"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
sCustomerId = .Cells(iRowNo, 1)
sFirstName = .Cells(iRowNo, 2)
sLastName = .Cells(iRowNo, 3)
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Execute "INSERT into dbo.Customers (CustomerId, FirstName, LastName) values ('" & sCustomerId & "', '" & sFirstName & "', '" & sLastName & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Customers Exported To Database"
conn.Close
Set conn = Nothing
End With
End Sub
问:我需要将数据存储在数组中,然后将它们推送到数据库吗?
提前致谢。
您不应对要导出的每一行使用插入查询。相反,如果您想手动执行此操作,请打开记录集:
Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim iRowNo As Integer
Dim sCustomerId, sFirstName, sLastName As String
With Sheets("Customers")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=TESTpc\SQLEXPRESS;Initial Catalog=ExcelSQLServerDemo;Trusted_connection=yes"
conn.CursorLocation = adUseClient 'Use a client-side cursor
rs.Open "SELECT * FROM dbo.Customers", conn, adOpenDynamic, adLockOptimistic 'Open the table into a recordset
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
rs.AddNew 'Add a new row
rs!CustomerId = .Cells(iRowNo, 1) 'Set row values
rs!FirstName = .Cells(iRowNo, 2)
rs!LastName = .Cells(iRowNo, 3)
rs.Update 'Commit changes to database, you can try running this once, or once every X rows
iRowNo = iRowNo + 1
Loop
MsgBox "Customers Exported To Database"
conn.Close
Set conn = Nothing
End With
End Sub
这具有若干优点,包括但不限于增加的性能,插入引用值的能力和增加的稳定性。