我目前正在尝试将一个查询SQL Server的项目从VBA从ODBC移到ADODB。引用了Active X数据对象和Recordset 2.8。
ADODB连接正常工作,并填充Recordset。似乎出于某种我无法理解的原因,重新设置和查询表彼此不喜欢。我在连接对象上尝试了任何类型的With。
我遇到运行时错误'1004'应用程序定义或对象定义的错误。
这是代码的样子:
Dim cn As Object
Dim rs As Object
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
With cn
.Open "Driver={SQL Server};Server=xxx;Database=xxx;UID=xxx;PWD=xxx;"
.CommandTimeout = 0
Set rs = .Execute("Select 1")
End With
Debug.Print rs(0)
Dim qtData As QueryTable
Set qtData = ActiveSheet.QueryTables.Add(rs, Destination:=Range("A1"))
With qtData
.Name = "DTBase"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = False
.BackgroundQuery = False
.EnableEditing = False
End With
'ActiveSheet.ListObjects.Add(xlSrcQuery, rs, Destination:=Selection).QueryTable.Refresh
qtData.Refresh
qtData.Close
qtData.Delete
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
本质上,您在使用不同方法时遇到两个问题:
[.Close
:因为QueryTable对象没有.Close
方法,所以只需删除该调用。
[.Debug.Print
:当您调用Debug.Print rs(0)
时,您显然消耗了记录集,因此不适用于QueryTables.Add()
,后者似乎需要未更改的记录集。
要解决,请考虑移动Debug.Print
之后 QueryTables.Add()
并在查询表将光标移到MoveFirst
的末尾之前调用EOF = True
。
Set qtData = ActiveSheet.QueryTables.Add(rs, Destination:=Range("A1"))
With qtData
.Name = "DTBase"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = False ' REMOVED REPEATED LINE AFTER THIS ONE
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = False
.EnableEditing = False
.Refresh ' MOVED TO INSIDE With BLOCK
.Delete ' MOVED TO INSIDE With BLOCK
End With
rs.MoveFirst
Debug.Print rs(0)
注意:我确实尝试在MoveFirst
之后运行Debug.Print
无济于事。似乎QueryTables.Add()
要求一个不变的记录集,而不管光标的位置如何。这可能与ODBC驱动程序不同。
Debug.Print rs(0)
rs.MoveFirst
Set qtData = ActiveSheet.QueryTables.Add(rs, Destination:=Range("A1"))
With qtData
...
.Refresh
.Delete
End With