使用Excel宏打开DB2数据库

时间:2017-04-05 07:51:48

标签: excel vba db2

我想用Excel宏打开Db2数据库并将数据填充到表格中。

Sub db()
Dim conn As Object
Dim rs As Object
Dim sqls As String
Set conn = CreateObject("ADODB.Connection")
conn.Open "Provider=MSDASQL;Database=SAMPLE;Hostname=localhost;             
Protocol=TCPIP;Port=50000;Uid=myuid;Pwd=mypw;"
Set rs = CreateObject("ADODB.Recordset")
rs.Open sqls, conn
Sheets("Sheet1").Range("A1").CopyFromRecordset rs
rs.Close
End Sub

但我收到以下错误

我想打开在db2中创建的示例表。 我该做什么? THX

1 个答案:

答案 0 :(得分:0)

您可以使用此代码:

Sub DB2connect()

  'Create the Connection String with Provider and Data Source options

   dim sSQLQry As String
   dim ReturnArray

   dim conn As New ADODB.Connection
   dim mrs As New ADODB.Recordset
   dim DBPath As String, sconnect As String

   Set wb = ThisWorkbook
   Set ws = wb.Sheets(1)

    ws.Activate

    DBPath = ThisWorkbook.FullName 'Refering the sameworkbook as Data Source

    sconnect = "Provider=MSDASQL.1;DSN=MyODBC connection name;UID=myuid;PWD=myPass;DBQ=myDatabase" & DBPath & ";HDR=Yes';"

    conn.ConnectionTimeout = 30
    conn.Open sconnect

    sSQLSting = " select * from table where ...."

    mrs.Open sSQLSting, conn

    'Import Headers
    For i = 0 To mrs.Fields.Count - 1
       ws.Range("B15").Offset(0, i) = mrs.Fields(i).Name
    Next i

    Range("B15").Offset(1, 0).CopyFromRecordset mrs

    mrs.Close
    conn.Close
    Set mrs = Nothing
    Set conn = Nothing



End Sub

<强> hier is the code in Github