简体   繁体   English

VBA将单元格分配为数组公式

[英]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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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