![](/img/trans.png)
[英]How would I use VBA to automatically populate an excel worksheet with data from the pivot table of a separate excel workbook?
[英]Excel VBA Using pivot table data in another workbook
以下Sub要求用户选择要打开的通用模板,然后要求用户选择源文件(以填充模板)。 源文件包含许多工作表和数据透视表。 子然后从数据透视表中选择数据并将其复制到模板中。 我需要源文件是变量,而不是硬编码数据透视表源bc,此标题根据用户选择而变化。
问题1:复制数据时,仅显示REF! 而不是实际数据(即使存在数据)。
'Open Generic Report to populate with data
Dim GenericFolderLocation As String
MsgBox "Please select the generic porfolio template..."
GenericFolderLocation = "C:\Users\user.name\Desktop"
ChDrive GenericFolderLocation
SelectedFile = Application.GetOpenFilename( _
fileFilter:="Excel Files (*.xls*), *.xls*", MultiSelect:=False)
Workbooks.Open (SelectedFile)
Set test = ActiveWorkbook
Dim SourceFolderLocation As String
Dim FileName As String
Dim SourceFile As String
MsgBox "Please select the data source file..."
SourceFolderLocation = "C\Users\user.name\Desktop"
ChDrive SourceFolderLocation
SourceFile = Application.GetOpenFilename( _
fileFilter:="Excel Files (*.xls*), *.xls*", MultiSelect:=False)
Workbooks.Open (SourceFile)
Set wkbk = ActiveWorkbook
test.Activate
'Test1
'Select empty cell in Chart template
Range("C28").Select
'Populate with pivot table data from sourceFile
ActiveCell.FormulaR1C1 = _
"=GETPIVOTDATA("" Value"",'[wkbk]ActCost_PIVOT'!R3C1,""Team"",""Field1"",""Row Descrption"",""Row1"",""Type"",""DataPoint1"")"
'Repeat for next cell
Range("C27").Select
ActiveCell.FormulaR1C1 = _
"=GETPIVOTDATA("" Value"",'[wkbk]CRActCost_PIVOT'!R3C1,""Team"",""Field1"",""Row Descrption"",""Row1"",""Type"",""DataPoint2"")"
[已解决]问题2。类似于问题1,我想制作“ TypeName”或“ TeamName”变量。 我可以这样在Sub外部声明它们吗?
Dim TeamName As String
Sub()
TeamName = "Tigers"
End Sub
谢谢你的帮助!
在VBA中定义全局变量(在任何子/函数之外)没有问题。 您为TeamName
提出的建议就可以了(在给定模块的顶部编写变量define)。 之后,您可以在此模块内使用此变量,而不会出现任何问题。 例如,通过执行以下操作:
ActiveCell.FormulaR1C1 = _
"=GETPIVOTDATA("" Sum"",'[SourceFile]WorkbookA_PIVOT1'!R3C1,""Team/Branch""," & """" & TeamName & """" & ",""Row Descrption"",""RowName"",""Type"",""TypeName"")"
如您所见,在需要引号的情况下(转义),您必须加以注意。 避免混淆的技巧是将它们完全放在适当的位置(“”“”),如上所示。
我想强调的另一个问题是,您可以直接通过VBA访问任何PivotTable
所有内容(您的问题中不需要公式):
Dim pivotTable As pivotTable
Set pivotTable = ActiveSheet.PivotTables("PivotTable Name")
从pivotTable
变量中,您可以完全访问给定PivotTable的所有内容。 这代表了VBA优于Excel的优势,您应该将其最大化(如果继续依赖公式,为什么还要使用VBA?)。
我想它们在我前面提到的答案中是隐含的,但是为了确保这一点,这里有您对特定问题的回答:
&
s将其与其余位连接起来。 如果有引号,则必须按照上述建议将其转义。 TeamName
提议的代码是正确的,并且应该为要全局使用的任何其他(字符串)变量模拟它。 但是,请记住,过多的全局变量并不是一种好的编码习惯; 打算尽可能地依赖局部变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.