VBA ADO Excel-2010如何将ADO连接分配到数据透视表数据源

时间:2018-08-03 17:47:25

标签: excel vba ado

如何或如何在excel 2010中将ADO连接分配给数据透视表数据源?我想以此作为一种解决方法,以解决excel无法在未打开的情况下连接受密码保护的文件的情况。

我将在下面包括两个代码段。

用于遍历所有数据透视表以将数据源更改为现有连接的代码

Sub changeConnection()
  Dim pTable As Variant
  Dim sheet As Variant
  Dim workBookName As String 

  workBookName = "filename.xlsm"      

  For Each sheet In Workbooks(workBookName).Worksheets
    For Each pTable In sheet.PivotTables
     pTable.changeConnection Workbooks(workBookName ).Connections("connection name")
    Next pTable
   Next sheet

End Sub

在受密码保护的文件上创建ADO连接的代码。

 Public Function readFile()
  Dim xl As Object
  Dim conn As New ADODB.connection
  Dim recSet As ADODB.Recordset
  Dim conString As String
  Dim wkbName As String
  Dim SQL As String
  Dim DBPath As String

 'Path to excel file
 DBPath = "path\to\file.xlsm"
 Set xl = GetObject(DBPath)

'Name of table
wkbName = "[IS$]"

conString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"

'Query
SQL = "select * from " & wkbName

'Open connection
conn.Open conString

 'Itterate over record set
 Set recSet = New ADODB.Recordset
 recSet.Open SQL, conn

 'Print out col1 from table
  Do Until recSet.EOF
  'process your data here
  Debug.Print recSet!ISData
  recSet.MoveNext
  Loop
End Function

关于如何尝试的任何建议都很棒。我不想使用开放式工作簿,因为这意味着要由几个人使用。

提前谢谢!!!

0 个答案:

没有答案