简体   繁体   中英

How to give filepath to SUMIF() formula in VBA

=SUMIF('[filename1.xlsx]Sheet1'!$A:$A,C12,'[filename1.xlsx]Sheet1'!$Y:$Y)+SUMIF('[filename2.xlsm]Data from ABC'!$A:$A,C12,'[filename2.xlsm]Data from ABC'!$Y:$Y)

The above formula is being used in filename3 , however, if filename1 and filename2 are closed it gives and error and I have to set the entire formula again. To avoid this, how can we give the file name as a cell reference to sumif formula

I am using the following formula, wherein I have given the entire file name in cells A10, A11, B10, B11, but it is not working.

=SUMIF(A10,C12,A11+SUMIF(B10,C12,B11)

Can you please suggest a crack to this?

The function SUMPRODUCT can deal with closed workbooks. But the arguments in this function are in matrix (array) context and this is very unperformant for whole columns. So the following will only work, if you can shrink the ranges from whole columns to parts of columns.

Open the three files. In filename3 create the formula:

=SUMPRODUCT(('[filename1.xlsx]Sheet1'!$A$1:$A$1000=C12)*'[filename1.xlsx]Sheet1'!$Y$1:$Y$1000)
+SUMPRODUCT(('[filename2.xlsm]Data from ABC'!$A$1:$A$1000=C12)*'[filename2.xlsm]Data from ABC'!$Y$1:$Y$1000)

Now close filename1 and filename2. Now in the formula should be the complete paths to filename1 and filename2 and the values are updateable automatically.

Greetings

Axel

First, declare some variables to represent your files:

Dim f1 as Workbook, f2 as Workbook
Set f1 = Workbooks("filename1.xlsx")
Set f2 = Workbooks("filename2.xlsx")

Now you can access these objects in your code, and use their Path and Name property which will help build the formula string which relies on these once the workbook is closed:

When referencing formula like this, I think the syntax is:

'_workbook_path[_workbook_name_]_sheet_name'!_cell_address

So, something like this (untested, might need some tweaks if your filename/worksheet name has spaces/etc.)

ActiveCell.Formula = "=SumIf('" & f1.Path & "[" & f1.Name & "]Sheet1'!$Y:Y)+" & _
                     "SumIf('" & f2.Path & "[" & f2.Name & "]Data from ABC'!$Y:Y)"

Etc.

HOWEVER

It's not clear when/how you're implementing this, and there are probably better ways to obtain data fromw orkbooks which are not open, including ADODB and ExecuteExcel4Macro methods.

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