简体   繁体   English

在MS Excel VBA中使用Row()和Column()在公式中计算单元格地址

[英]Calculating Cell Addresses in Formula with Row() and Column() in MS Excel VBA

I have gotten so much excellent help from this site. 我从这个站点获得了很多出色的帮助。 This is my first question. 这是我的第一个问题。 I have googled all the wordings I can think of and looked at all possible related threads on this site and others, and cannot find an explanation. 我已经搜索了所有我能想到的措辞,并查看了该站点和其他站点上所有可能的相关主题,但找不到解释。

I am trying to automate a sheet into which a data table of variable size will be pasted. 我正在尝试自动化将可变大小的数据表粘贴到其中的工作表。

Here is the formula I am trying to replicate: 这是我要复制的公式:

=(C26-B26)/B26 (percent variation to previous month) =(C26-B26)/B26 (与上个月相比的变化百分比)

Edited to respond to a comment: This formula is in cell C28 in the sheet I am being asked to automate. 编辑以回应评论:此公式位于我被要求自动执行的工作表的单元格C28中。 So it is referring to cells two rows above and 1 column to the left of the cell where the formula is located. 因此,它是指公式所在的单元格上方两行和左侧一列的单元格。

Here is my code which the editor accepts: 这是编辑器接受的我的代码:

ActiveCell.Formula = "=(" & (Cells(Index(Row() - 2), Index(Col())).Address(False, False)) & "-" & Cells(Index(Row() - 2), Index(Col() - 1)).Address(False, False) & "/" & Cells(Index(Row() - 2), Index(Col() - 1)).Address(False, False) & ")"

When I run this, I get a compile error: Sub or Function not defined and the first instance of row is highlighted. 运行此命令时,出现编译错误: Sub or Function not defined ,并且突出显示了row的第一个实例。

It seems to me I read somewhere that one cannot calculate with Row() and Column() but I have not been able to find that again. 在我看来,我读过某个地方无法使用Row()Column()计算,但是我再也找不到了。 I have found many examples online of people using Row() and Column() in this way to find cells adjacent to the active cell. 我在网上找到了许多使用Row()Column()来查找活动单元格附近的单元格的示例。

I appreciate any help and suggestions. 感谢您的帮助和建议。

Thank you in advance. 先感谢您。

I'd determine the indices of your reference cell (the one that's not known). 我将确定您的参考单元格的索引(未知的索引)。 In the example below, I'm simply using the indices and converting them to characters from ASCII and concatenating the returned character and the row number. 在下面的示例中,我只是使用索引并将其转换为ASCII中的字符,然后将返回的字符和行号连接起来。

Dim activeRow, activeColumn As Integer
    activeRow = 40   'Iterate through or use Range reference as Range.Row
    activeColumn = 3 'Iterate through or use Range reference as Range.Column
    MsgBox ("=(" & Chr(64 + activeColumn) & (activeRow - 2) & "-" & Chr(64 + activeColumn - 1) & (activeRow - 2) & "/" & Chr(64 + activeColumn - 1) & (activeRow - 2) & ")")

Update: Also take a look at this question for referencing the instance of the calling cell in a Public Function, specifically Fionnuala 's answer. 更新:还请参见此 问题,以引用公共功能中调用单元的实例,特别是Fionnuala的答案。

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

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