问候,
下面的VBA代码将创建一个Excel QueryTable对象,并从Range(“D2”)开始显示它。该目标范围的具体地址并不重要。
我的问题是 - 是否可以手动将值输入到内存中的Recordset,然后从中读取表格?换句话说,我想在VBA中指定表列和值,而不是来自数据库或文件。
Public Sub Foo()
Dim blah As QueryTable
Dim rngTarget As Range
Dim strQuery As String
strQuery = "SELECT * FROM MY_TABLE"
Set rngTarget = Range("D2")
Dim qt As QueryTable
Set qt = rngTarget.Worksheet.QueryTables.Add(Connection:= _
"ODBC;DRIVER=SQL Server;SERVER=MY_SQL_SERVER;APP=MY_APP;Trusted_Connection=Yes", Destination:=rngTarget)
With qt
.CommandText = strQuery
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = False
.Name = "MY_RANGE_NAME"
.MaintainConnection = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = False
.RefreshPeriod = 0
.PreserveColumnInfo = False
.Refresh BackgroundQuery:=False
End With
End Sub
答案 0 :(得分:2)
是的,当然。
Dim vConnection As Variant, vCommandText As Variant
Dim r As ADODB.Recordset
Dim i As Long
'Save query table definition
vConnection = QueryTable.Connection
vCommandText = QueryTable.CommandText
Set r = New ADODB.Recordset
<populate r>
Set QueryTable.Recordset = r
QueryTable.Refresh False
'Restore Query Table definition
Set QueryTable.Recordset = Nothing
QueryTable.Connection = vConnection
QueryTable.CommandText = vCommandText
答案 1 :(得分:0)
从Excel VB帮助 连接参数可以是:
“ADO或DAO Recordset对象。从ADO或DAO记录集读取数据.Microsoft Excel保留记录集,直到删除查询表或更改连接。生成的查询表无法编辑”
所以是的,看起来你可以做到。