执行SQL时未设置VBA对象变量

时间:2014-09-04 03:20:11

标签: vba excel-vba excel

我一直在使用此代码,但我不知道代码是否有问题。

一切正常,直到执行查询为止。

以下是代码:

Dim i As Integer

ConnectDB
lastrow = Sheets("Sheet1").Cells(Sheets("Sheet1").Rows.Count, "H").End(xlUp).Offset(0, 0).Row
MsgBox (lastrow)

For i = 2 To lastrow
    get_id = Sheet1.Cells(i, 8).Value
    col1 = Sheet1.Cells(i, 9).Value
    col2 = Sheet1.Cells(i, 10).Value
    col3 = Sheet1.Cells(i, 11).Value
    mySQL = "UPDATE pegawai SET nama = '" & col1 & "', alamat = '" & col2 & "', tlp = " & col3 & " where id = " & get_id & ""
    MsgBox (mySQL)
    oConn.Execute (mySQL)  <---- ERROR HERE
    Set oConn = Nothing
Next i
oConn.Close

当我运行此代码时,我得到一个错误对象变量或未设置块变量。当我添加

Set oConn = New ADODB.Connection

它会产生错误

  

关闭对象时不允许操作

这是我的连接代码

Dim oConn As ADODB.Connection
Dim rs As ADODB.Recordset

Public Sub ConnectDB()
    Set oConn = New ADODB.Connection
    oConn.Open "DRIVER={MySQL ODBC 3.51 Driver};" & _
    "SERVER=localhost;" & _
    "DATABASE=belajar;" & _
    "USER=root;" & _
    "PASSWORD=;"
End Sub

为什么会出错?当你们都能提供帮助时,我感激不尽。

1 个答案:

答案 0 :(得分:2)

从FOR循环中移出Set oConn = Nothing

Dim i As Integer

ConnectDB
lastrow = Sheets("Sheet1").Cells(Sheets("Sheet1").Rows.Count, "H").End(xlUp).Offset(0, 0).Row
MsgBox (lastrow)

For i = 2 To lastrow
    get_id = Sheet1.Cells(i, 8).Value
    col1 = Sheet1.Cells(i, 9).Value
    col2 = Sheet1.Cells(i, 10).Value
    col3 = Sheet1.Cells(i, 11).Value
    mySQL = "UPDATE pegawai SET nama = '" & col1 & "', alamat = '" & col2 & "', tlp = " & col3 & " where id = " & get_id & ""
    MsgBox (mySQL)
    oConn.Execute (mySQL)  <---- ERROR HERE

Next i
oConn.Close