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

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”
未设置对象变量或带块变量。

我不明白我在做什么错。

最佳答案

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/

10-06 13:53