我对VBA几乎一无所知,但我正试图修改一个应用程序以连接到MySQL数据库。
下面的代码在rstProjets.Open处产生编译错误,我似乎找不到原因。

Public mysqlConn As ADODB.Connection

Private Sub cmdUpdate_Click()
Dim rstProjets As ADODB.Recordset
ConnectMySQL
Set rstProjets = rstProjets.Open("SELECT * FROM subventions LIMIT 5", mysqlConn)
With rstProjets
    If Not .EOF And Not .BOF Then
        .MoveFirst
        Do While Not .EOF
        MsgBox "Subventions:" & rstProjets![pin], , "Subvention ajoutée"
        .MoveNext
        Loop
    Else
        MsgBox "Aucune données à mettre à jour !", , "LVMB"
    End If
    .Close
End With
mysqlConn.Close
End Sub

Private Sub ConnectMySQL()
Set mysqlConn = New ADODB.Connection
mysqlConn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
    "SERVER=127.0.0.1;" & _
    "DATABASE=database;" & _
    "USER=root;" & _
    "PASSWORD=;" & _
    "Option=0"
End Sub

最佳答案

将rstProjets对象变量设置为New ADODB.Recordset,然后调用其.Open方法。

Dim rstProjets As ADODB.Recordset
ConnectMySQL
Set rstProjets = New ADODB.Recordset
rstProjets.Open "SELECT * FROM subventions LIMIT 5", mysqlConn

07-25 23:27