2

我希望能够将数据从 Excel 工作表加载到 SQL 服务器数据库。

我可以使用循环在 VBA 中一次一行地执行此操作,但如果我可以更进一步并进行连接,那就太好了。Remou此表单上发布的代码看起来很理想,但我无法让它工作。

我认为我很难过的地方是让 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
4

1 回答 1

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
于 2013-08-13T11:38:53.963 回答