尝试使用VBA从MySQL提取数据到Excel

时间:2017-02-16 16:36:40

标签: mysql excel vba

我收到错误,我不明白是什么问题。这是我的代码

Sub test()
Dim rs As ADODB.Recordset
Dim sqlstr As String ' SQL to perform various actions
Dim oConn As ADODB.Connection

    Set oConn = New ADODB.Connection
    oConn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
        "SERVER=ETS-DEV-01;" & _
        "DATABASE=reporting;" & _
        "USER=guest_user;" & _
        "PASSWORD=0X4ZT9kwsY%yGOp;" & _
        "Option=3"
    sqlstr = "select * from tveuptimes"
    rs.Open sqlstr, oConn

End Sub

我收到错误: 运行时错误'91' 对象变量或未设置块变量。

我不明白我做错了什么。

1 个答案:

答案 0 :(得分:1)

Set oConn = New ADODB.Connection并非必要。相反,当您标注rsoConn时,请在类型之前添加单词New,如下所示:

Sub test()
Dim rs As New ADODB.Recordset
Dim sqlstr As String
Dim oConn As New ADODB.Connection

    oConn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
        "SERVER=ETS-DEV-01;" & _
        "DATABASE=reporting;" & _
        "USER=guest_user;" & _
        "PASSWORD=0X4ZT9kwsY%yGOp;" & _
        "Option=3"
    sqlstr = "select * from tveuptimes"
    rs.Open sqlstr, oConn

End Sub

这是一个很好的教程:http://analysistabs.com/excel-vba/ado-sql-macros-connecting-database/