如何使用VBA在Excel中添加连接(到外部数据源)并将其保存到该Excel电子表格的连接列表

我可以使用VBA创build一个新的ADODB.Connection和关联的ADODB.Command和ADOBD.Parameter,然后创build一个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 

…但是在运行这个macros之后,如果我检查连接列表中的连接属性(在function区的数据选项卡中),它们将显示为禁用(灰色),并且SQL命令不会显示在那里只通过VBA进行更改)。

我如何创build这些相同的对象,但让他们与Excel用户界面集成,以便将来的用户不需要使用VBA? 有任何想法吗?

您可以使用macroslogging器来生成一个VBA代码,将添加到您的Excel实例的连接。
我在这个答案的末尾添加了代码,但是如果您按照以下步骤操作,则可以生成自己的代码:
1)启动一个macroslogging器
2)在function区上,单击Data选项卡。 点击Connections ,然后selectAddbutton,如下图所示
第2步
3)在下一个屏幕上,select您现有的数据库连接,并按照接下来的2或3个屏幕上的步骤configuration您的连接。
4)build立连接并出现在连接列表中后,单击Propertiesbutton,然后在下一个屏幕Export Connection File
4
5)停止macroslogging器,打开VBE (alt+F11)并编辑你的Module1的代码6)从你的macros代码中删除这些行

 .ServerFillColor = False .ServerFontStyle = False .ServerNumberFormat = False .ServerTextColor = False 

7)现在保存并closures文件

请注意,当您重新打开文件并运行macros时,应将连接添加到连接列表中

您现在可以使用此代码从导出的文件中添加连接

 Workbooks("Book1").Connections.AddFromFile _ "C:\Users\...\exported_file_name.odc" 

或者可以运行录制的代码,让macros为你添加它