Sam*_*Sam 10 excel vba pivot-table
我可以使用VBA创建一个新的ADODB.Connection和相关的ADODB.Command和ADOBD.Parameter,然后创建一个PivotCache和一个数据透视表
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
Run Code Online (Sandbox Code Playgroud)
...但是,在运行此宏之后,如果我检查Connections列表中的连接属性(在功能区的"数据"选项卡中),它们将显示为禁用(灰显),并且SQL命令不会出现在那里(进一步限制)仅通过VBA进行更改).
如何创建这些相同的对象,但是将它们与Excel UI集成,以便将来的用户不需要使用VBA?有任何想法吗?
小智 8
您可以使用宏录制器生成VBA代码,该代码将添加与excel实例的连接.
我已在此答案的末尾添加了代码,但是如果您按照以下步骤操作,则可以生成自己的代码:
1)启动宏录制器
2)在功能区上,单击Data
选项卡.单击Connections
,然后选择Add
按钮,如下面的屏幕截图所示
3)在下一个屏幕上,选择现有的数据库连接,然后按照接下来的2或3个屏幕上的步骤配置连接.
4)建立连接并显示在连接列表中后,单击Properties
按钮并在下一个屏幕上Export Connection File
5)停止宏录制器并打开并编辑
6)中的代码从宏代码中删除这些行VBE
(alt+F11)
Module1
.ServerFillColor = False
.ServerFontStyle = False
.ServerNumberFormat = False
.ServerTextColor = False
Run Code Online (Sandbox Code Playgroud)
7)立即保存并关闭文件
请注意,重新打开文件并运行宏时,应将连接添加到连接列表中
您现在可以使用此代码添加导出文件中的连接
Workbooks("Book1").Connections.AddFromFile _
"C:\Users\...\exported_file_name.odc"
Run Code Online (Sandbox Code Playgroud)
或者可以运行录制的代码并让宏为您添加
归档时间: |
|
查看次数: |
42974 次 |
最近记录: |