tôi sao chép một đoạn mã VBA từ MSDN cho thấy tôi làm thế nào để lấy kết quả từ một truy vấn SQL vào excel sheet (Excel 2007):Cơ sở dữ liệu Truy cập SQL trong Excel VBA
Sub GetDataFromADO()
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;User ID=abc;Password=abc;"
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = "select * from myTable"
objMyCmd.CommandType = adCmdText
objMyCmd.Execute
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open objMyCmd
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
End Sub
tôi đã thêm Microsoft Đối tượng dữ liệu ActiveX 2.1 Thư viện dưới dạng tham chiếu. Và cơ sở dữ liệu này có thể truy cập được.
Bây giờ, khi tôi chạy chương trình con này, nó có một lỗi:
Run-time error 3704: Hoạt động không được phép khi đối tượng được đóng lại.
Trên tuyên bố:
ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
Bất cứ ý tưởng tại sao?
Cảm ơn.
Help! Tôi gặp lỗi tương tự, nhưng các giải pháp dưới đây không giúp được: http://stackoverflow.com/questions/1682717/vba-adodb-run-time-error-3704 – Steven