简体   繁体   中英

VBA to assign a cell as an array formula

I have a sheet called "Total" that I have to duplicate which contains an array formula. When I create a copy and rename it, the array formula is no longer entered as an array.

when I record a macro its looks like the following.

Range("B55").Select
    Selection.FormulaArray = _
        "=IF(R1C1=""Total"",INDEX('[All_File.xlsm]Sheet1'!R4C5:R8C5,MATCH(R[-53]C,'[All_File.xlsm]Sheet1'!R4C2:R8C2,0)),INDEX('[All_File.xlsm]Sheet1'!R5,MATCH(R1C1&""Groups"",'[All_File.xlsm]Sheet1'!R4&'[All_File.xlsm]Sheet1'!R3,0)))"

This issue with this is that it is referencing the file in the formula. The file reference can change so this recorded macro would not work.

Is there a way to select a cell and have it be entered as an array?

For example:

 Range("B55").Select
        Selection.FormulaArray

the cell is being selected and entered as an array. Again my issue with the recorded macro is that it is storing the file name, which will change, so the recorded macro cant be used again.

You can replace the file name before adding the formula:

Dim f As String, myFile

f = "=IF(R1C1=""Total"",INDEX('[{file}]Sheet1'!R4C5:R8C5,MATCH(R[-53]C," & _ 
    "'[{file}]Sheet1'!R4C2:R8C2,0)),INDEX('[{file}]Sheet1'!R5," & _ 
    "MATCH(R1C1&""Groups"",'[{file}]Sheet1'!R4&'[{file}]Sheet1'!R3,0)))"

myFile = 'get your filename here...    

Range("B55").FormulaArray = Replace(f, "{file}", theFilename)

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