我可以使用VBA創建新的ADODB.Connection和關聯的ADODB.Command和ADOBD。參數,然後創建一個PivotCache和數據透視表如何使用VBA在Excel中添加連接(到外部數據源)並將其保存到該Excel電子表格的連接列表
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?有任何想法嗎?
您是否暗示連接沒有保存在xls文件中,但可以將它們導出到下次打開xls文件時加載的.odc文件中? – Sam
如果你不斷丟失連接字符串,那麼這是一個解決方法從保存的文件中檢索它。如果你重新調用它,那麼所有使用你的Excel電子表格的人都可以擁有自己的連接字符串導出/導入。 – 2013-07-02 07:06:20
感謝您的幫助。 – Sam