在VBA中关闭对象时不允许操作

时间:2015-04-01 09:48:23

标签: excel vba excel-vba sql-server-2008-r2

我是这个网站的新手,也是VBA的新手, 一些我如何设法编写VBA,但遇到上述错误。如果我的代码有任何变化,请告诉我。感谢

Option Explicit
Const ConStrSql As String = "----"



Sub CopyDataFromDatabase()

Dim DataConn As ADODB.Connection
Dim StaffData As ADODB.Recordset
Dim DataFiels As ADODB.Field

Set DataConn = New ADODB.Connection
Set StaffData = New ADODB.Recordset

DataConn.ConnectionString = ConStrSql
DataConn.Open

On Error GoTo CloseConnection

With StaffData
.ActiveConnection = DataConn
.Source = "select ---"
.LockType = adLockReadOnly
.CursorType = adOpenKeyset

End With

On Error GoTo CloseRecordset

Worksheets.Add

For Each DataFiels In StaffData.Fields
ActiveCell.Value = DataFiels.Name
ActiveCell.Offset(0, 1).Select
Next DataFiels

Range("A1").Select
Range("A2").CopyFromRecordset StaffData
Range("A1").CurrentRegion.EntireColumn.AutoFit

CloseRecordset:
StaffData.Close


CloseConnection:
DataConn.Close




End Sub

当我删除 CloseRecordset: StaffData.Close

我在excel中列出了列,但没有列出数据

请任何建议。感谢

1 个答案:

答案 0 :(得分:1)

您的代码定义了Recordset但未打开它。添加:

StaffData.Open

之前:

Range("A2").CopyFromRecordset StaffData

应该解决问题。