【问题标题】:Excel VBA to sum cells backwards based on a variable number of cells?Excel VBA根据可变数量的单元格向后汇总单元格?
【发布时间】:2020-07-30 06:37:33
【问题描述】:

我需要编写一个代码,将单元格添加到同一行但向后添加 3 列,然后每个单元格向后添加 4 列一定次数。我想在输入框中输入一个数字并让它添加 3 列,然后添加 4 列,就像我在输入框中所说的那样多次。

例如,如果我选择了 range("AS2"),运行宏,然后在输入框中输入 4,AS2 中打印的公式将是“=AP2+AL2+AH2+AD2”。如果我在输入框中输入 6,AS2 中的公式将是“=AP2+AL2+AH2+AD2+Z2+V2”

我目前的工作是这样的:

I2 = Selection.Column
I3 = 3 'I3 will be changed to inputbox.  practicing adding 2 rows backwards 3 times for now

rngS = Replace(Cells(2, (I2 - 2)).Address, "$", "")
FormulaS = "=" & rngS

For I = 2 To I3

rngS = Replace(Cells(2, I2 - (2 * I)).Address, "$", "")
FormulaS = FormulaS & "+" & rngS

Next I

Cells(2, I2).Value = FormulaS

谢谢,

【问题讨论】:

  • 看起来很简单。您已经尝试过什么?
  • @BigBen 到目前为止,我正在处理的内容如下所示: [code]I2 = Selection.Column I3 = 3 'I3 将在代码完善后更改为输入框。现在练习向后添加 4 行 3 次 rngS = Replace(Cells(2, I2 - 4).Address, "$", "") Debug.Print rngS For I = 1 To I3 FormulaS = rngS & "+" & rngS = Replace(Cells(2, I2 - (4 * I)).Address, "$", "") 接下来我 [code] 将代码添加到原始帖子,因为我不知道如何使评论看起来像样。跨度>

标签: excel vba


【解决方案1】:

使用Selection.Column 获取所选单元格的列号。现在,您可以简单地从获得的列号中减去输入值并获得下一个单元格的列号。现在,您需要使用Cells(Selection.Row, obtainedColumnNumber).Address 获取单元格的地址(如果您需要相对引用,请添加False, False)。然后,只需将获取的地址用加号连接起来,并在开头添加等号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多