我可以使用 VBA 创建一个新的 ADODB.Connection 和关联的 ADODB.Command 和 ADOBD.Parameter,然后创建一个 PivotCache 和一个 PivotTable
Sub CreatePivotTable()
'Declare variables
Dim objMyConn As ADODB.Connection
Dim objMyCmd As ADODB.Command
Dim objMyParam As ADODB.Parameter
Dim objMyRecordset As ADODB.Recordset
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=myMIS;Data Source=localhost;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=WKSTN101;Use Encryption for Data=False;Tag with column collation when possible=False"
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = "select a.col1, a.col2, b.col3, b.col4" & _
"from TableA a, TableB b " & _
"where a.col3=b.col5 " & _
"and a.col1=?"
objMyCmd.CommandType = adCmdText
Set objMyParam = objMyCmd.CreateParameter("COLUMN1", adChar, adParamInput, 20, Range("AnotherSheet!A3").Value)
objMyCmd.Parameters.Append objMyParam
'Open Recordset'
Set objMyRecordset.Source = objMyCmd
objMyRecordset.Open
'Create a PivotTable cache and report.
Set objPivotCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlExternal)
Set objPivotCache.Recordset = objMyRecordset
objPivotCache.CreatePivotTable TableDestination:=Range("A11"), TableName:="PivotTable1"
With ActiveSheet.PivotTables("PivotTable1")
.SmallGrid = False
With .PivotFields("Col3")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Col4")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("Col1")
.Orientation = xlColumnField
.Position = 1
End With
With .PivotFields("Col2")
.Orientation = xlDataField
.Position = 1
End With
End With
...但是在我运行这个宏之后,如果我检查连接列表中的连接属性(在功能区的数据选项卡中),它们会显示为禁用(灰色)并且 SQL 命令不会出现在那里(进一步限制仅通过 VBA 更改)。
我怎样才能创建这些相同的对象,但让它们与 Excel UI 集成,这样未来的用户就不需要使用 VBA?有任何想法吗?