我希望能够将Excel工作表中的数据加载到SQL Server数据库。
我能够使用循环一次一行地在VBA中执行此操作,但如果我可以更进一步并且也可以进行连接,那将会很棒。 Remou在此表单here上发布的代码看起来很理想,但我无法使其正常运行。
我认为我感到难过的是让VBA在excel中正确识别表格。在Remou提供的代码中,只有[Sheet2 $]的连接;无论我如何尝试定义我的Excel数据,我都会收到“无效的对象名称”错误。理想情况下,我想要连接的数组将被定义为excel中的表。
VBA识别用于连接的表需要什么? 任何建议/提示都非常感谢。
Dim cnTrans As New ADODB.Connection
''You should probably change Activeworkbook.Fullname to the
''name of your workbook
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& ActiveWorkbook.FullName _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
s = "INSERT INTO [ODBC;Description=TEST;DRIVER=SQL Server;" _
& "SERVER=Server;Trusted_Connection=Yes;" _
& "DATABASE=test].SomeTable ( Col1, Col2, Col3, Col4 ) " _
& "SELECT a.Col1, a.Col2, a.Col3, a.Col4 " _
& "FROM [Sheet2$] a " _
& "LEFT JOIN [ODBC;Description=TEST;DRIVER=SQL Server;" _
& "SERVER=Server;Trusted_Connection=Yes;" _
& "DATABASE=test].SomeTable b ON a.Col1 = b.Col1 " _
& "WHERE b.Col1 Is Null"
cn.Execute s
答案 0 :(得分:1)
如何使用表地址而不是表名?
Option Explicit
Sub test()
Dim listObj As ListObject
Dim tableName As String
Dim HeaderRange As String
Dim DataRange As String
Dim ws As Worksheet
Dim cnn1 As New ADODB.Connection
Dim rst1 As New ADODB.Recordset
Dim strSQL As String
Dim arrData() As Variant
'Ensure reference is set for ActiveX Data Objects X.y (eg 6.1)
tableName = "TableName1"
Set ws = Sheet1
Set listObj = ws.ListObjects(tableName) 'Table Name
'get range of Table
HeaderRange = listObj.HeaderRowRange.Address
DataRange = listObj.DataBodyRange.Address
cnn1.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=""Excel 12.0;HDR=No;IMEX=1"";"
strSQL = "SELECT * FROM [" & ws.Name & "$" & Replace(DataRange, "$", "") & "];"
rst1.Open strSQL, cnn1, adOpenStatic, adLockReadOnly
arrData = rst1.GetRows
rst1.Close
cnn1.Close
Set rst1 = Nothing
Set cnn1 = Nothing
Set listObj = Nothing
Set ws = Nothing
End Sub