简体   繁体   中英

Excel file name variable reference from cell

I have an excel formula which uses GETPIVOTDATA to get a value from another files pivot.

The formula I have references 5 locations in 4 other files which are updated every month and totals them up in the main file.

I have the files open to do this.

The issue I have is I have to manually update the file names in the formula each month to get them to look at the latest file.

My current formula which I have to manually update:

=GETPIVOTDATA("Add YTD ",'[FileA P6 2018.xlsm]Monthly report'!$A$5)
+GETPIVOTDATA("Add YTD ",'[FileA P6 2018.xlsm]Monthly sub report'!$A$39)
+GETPIVOTDATA("Add YTD ",'[FileB P6 2018.xlsm]Monthly pivot'!$A$3)
+GETPIVOTDATA("Add YTD ",'[FileC P6 2018.xlsm]Monthly report'!$A$5)
+GETPIVOTDATA("Add YTD ",'[FileD P6 2018.xlsm]Monthly pivot'!$A$3)

And next month the file names will change the P6 to P7 .

I have two cells with the values I want use in the variable:

B4 = 6
B5 = 2018

I have tried the following to no avail:

=GETPIVOTDATA("Add YTD ",'[FileA P$B$4 $B$5.xlsm]Monthly report'!$A$5)
+GETPIVOTDATA("Add YTD ",'[FileA P$B$4 $B$5.xlsm]Monthly sub report'!$A$39)
+GETPIVOTDATA("Add YTD ",'[FileB P$B$4 $B$5.xlsm]Monthly pivot'!$A$3)
+GETPIVOTDATA("Add YTD ",'[FileC P$B$4 $B$5.xlsm]Monthly report'!$A$5)
+GETPIVOTDATA("Add YTD ",'[FileD P$B$4 $B$5.xlsm]Monthly pivot'!$A$3)

I think you'll need the INDIRECT formula, which enables you to build up the reference using variables. For example, the below enables you to access cell E12 in a workbook

=INDIRECT("[FileA"&B4&B5&".xlsm]Sheet1!$E$12")

I'm not 100% sure how you want to combine that the GETPIVOTDATA - I think you can put the GETPIVOTDATA call inside the INDIRECT call, but will have to be careful with escaping " ...

This was resolved with VBA and setting the cells B4 and B5 too:

B4 = P5 2017
B5 = P6 2018

VBA:

Sub FileNameUpdate()
    Cells.Replace What:=Range("B4") & ".xlsm", Replacement:=Range("B5") & ".xlsm", _
                  LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
                  SearchFormat:=False, ReplaceFormat:=False
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM