对象打开时不允许3705操作

时间:2016-10-05 07:55:53

标签: database excel-vba vba excel

我在Excel表单中有一些数据,我想将其导入数据库。我还想从数据库中检索一些数据。我使用VBA连接到数据库,我的代码给了我一个错误。

以下是代码:

Sub Button1_Click()


   Dim conn As New ADODB.Connection
   Dim rs As New ADODB.Recordset


       'Open a connection to SQL Server
       conn.Provider = "sqloledb"
       conn.Properties("Prompt") = adPromptAlways
       conn.Open "Data Source=localhost;Initial Catalog=bank;"

       'conn.Open "Provider=SQLOLEDB;Data Source=ASUSBOOK\SQL2012;Initial Catalog=ExcelDemo;Integrated Security=SSPI;"
       Set rs.ActiveConnection = conn
           rs.Open "select code from info"
           startrow = 2

           Do Until rs.EOF
           Cells(startrow, 5) = rs.Fields(0).Value


           rs.MoveNext
           startrow = startrow + 1

           Loop

           rs.Close
           Set rs = Nothing


    Dim iRowNo As Integer
    Dim accountno, Amount, code As String
    Dim Rowcount As Integer
    Rowcount = 1


    With Sheets("Sheet1")


        iRowNo = 2

            Do Until .Cells(iRowNo, 1) = ""
            accountno = .Cells(iRowNo, 1)
            Amount = .Cells(iRowNo, 2)
            .Cells(iRowNo, 3) = "OK"
            .Cells(iRowNo, 4) = Rowcount
            .Cells(iRowNo, 5) = Post_Date

            'Generate and execute sql statement to import the excel rows to SQL Server table
            conn.Provider = "sqloledb"
            conn.Properties("Prompt") = adPromptAlways
            conn.Open "Data Source=localhost;Initial Catalog=bank;"
            conn.Execute "insert into dbo.Customers (AccountNo,Amount,code) values ('" & accountno & "', '" & Amount & "', '" & code & "')"

            iRowNo = iRowNo + 1
            Rowcount = Rowcount + 1
            DoEvents

        Loop

        MsgBox "Customers imported."

        conn.Close
        Set conn = Nothing

    End With




End Sub

1 个答案:

答案 0 :(得分:0)

将ADO Recordset的CursorLocation属性设置为adUseClient

conn.CursorLocation = adUseClient