简体   繁体   English

在VBA Excel中引用公式内的一系列单元格

[英]Referring to a range of cells inside a formula in VBA Excel

I'm trying to use VBA in order to Calculate some fields. 我正在尝试使用VBA来计算一些字段。 When I record a macro I get this: 当我记录一个宏时,我得到这个:

ActiveCell.FormulaR1C1 = "=AVERAGEIF(R4C[-27]:R4C[-6],2012,RC[-27]:RC[-6])"

The problem is that the range for the formula can change. 问题在于公式的范围可以更改。

I have an Integer variable NumOfMon which counts the required columns for the formula from the first column on the sheet. 我有一个整数变量NumOfMon ,它从工作表的第一列开始计算公式所需的列。 The formula above however, uses offsets to determine the required range but because my range can change I need to use the NumOfMon in order to use only the required cells. 但是,上面的公式使用偏移量来确定所需的范围,但是由于我的范围可以更改,因此我需要使用NumOfMon才能仅使用所需的单元格。 How can I change the formula so I can use it properly? 如何更改公式以便可以正确使用?

I tried using variables like this: 我尝试使用这样的变量:

a = 28
NumofMon = 21
 ActiveCell.FormulaR1C1 = "=AVERAGEIF(R4C[-(a-1)]:R4C[-(a-NumOfMon-1)],2012,RC[-(a-1)]:RC[-(a-NumOfMon-1)])"

but I get an error: "application defined or object defined error" 但出现错误:“应用程序定义或对象定义错误”

基本上

ActiveCell.FormulaR1C1 = "=AVERAGEIF(R4C[-" & (a-1) & "]:R4C[-" & (a-NumOfMon-1) & "],2012,RC[-" & (a-1) & "]:RC[-" & (a-NumOfMon-1) & "])"

If it is possible, turn your data into a table. 如果可能,将您的数据转换为表格。 This way, you can refer to dynamic data (changing in size) without running into problems. 这样,您可以引用动态数据(大小变化)而不会遇到问题。 For instance, to refer to column A, called 'Item' in a table called 'Table1', your reference would be '=Table1[Item]' Regardless of the rows. 例如,要引用名为“ Table1”的表中名为“ Item”的列A,您的引用将是“ = Table1 [Item]”,无论行如何。

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

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