VBA – 迭代列名称

我正在跨多个列进行相同types的操作。 例如,我的代码目前工作,当我这样做:

Cells(lRow, "D") = Cells(lRow, "D") + Cells(lRow + 1, "D") Cells(lRow, "E") = Cells(lRow, "E") + Cells(lRow + 1, "E") ' .... ' Cells(lRow, "AA") = Cells(lRow, "AA") + Cells(lRow + 1, "AA") Cells(lRow, "AB") = Cells(lRow, "AB") + Cells(lRow + 1, "AB") 

在上面的代码中,我将从D列到AB列,并在每列添加我正在查看的当前行的值和它下面的行的值。 结果代码几乎是30行,大部分是复制和粘贴,这只是一个讨厌的问题。

我正在尝试重构此代码,以便可以将列名(Cell函数调用中的第二个参数)分解出来。 我正在考虑使用for循环,从列“D”迭代到列“AB”,并执行加法操作。

 ' iterate from column D to column AB and at each column do the operation below ' For c = "D" To "AB" Cells(lRow, c) = Cells(lRow, c) + Cells(lRow + 1, c) Next c 

这是行不通的,因为看起来VBA不允许在字符(从“D”到“AB”)上迭代(for循环)。

我已经看到其他解决scheme涉及整数,并将其转换为字符(A = 1,B = 2,C = 3,D = 4等),但不能得到这个工作。 我认为这看起来像这样:

 ' integer to character mapping: A = 1, B = 2, C = 3, D = 4, ... , AA = 27, AB = 28 ' For i = 4 To 28 colNameFromInt = Chr(ascii) Cells(lRow, colNameFromInt) = Cells(lRow, colNameFromInt) + Cells(lRow + 1, colNameFromInt) Next i 

简而言之,如果我向你展示了从顶端开始的〜30行代码,你将如何压缩它?

谢谢!

列可以用一个数字来处理。 由于您已经在使用Cells(),只需使用列号而不是字母

 Dim c As Integer For c = 5 To 10 Cells(1, c) = "this is column " & c Next c 

这将改变列E到I的单元格。

或者在你最初的例子中缩短代码

 Dim c As Integer Dim lrow As Long lrow = 2 ' or however you arrive at a value for this variable For c = 4 To 28 Cells(lrow, c) = Cells(lrow, c) + Cells(lrow + 1, c) Next c 

您可以遍历范围,然后使用偏移属性
就像是:

 Dim cel As Range For Each cel In Range("D1:AB1") cel.Offset(lrow - 1, 0) = cel.Offset(lrow - 1, 0) + cel.Offset(lrow, 0) Next