简体   繁体   English

跨列循环公式

[英]Loop Formula Across Columns

I'd like to loop a formula across columns and have it stop when it gets to the last column that I have defined. 我想跨列循环公式,并在到达我定义的最后一列时使其停止。 Here is the code: 这是代码:

Sub LoopAcrossCols()
Dim LastCol As Integer
Worksheets("Sheet1").Activate
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
Column = 3
Do
Cells(2, Column).Formula = "=B2+C3"

Row = Row + 1

Loop Until LasCol

End Sub

Just to be clear, the formula would change as the loop goes from column to column. 需要明确的是,公式会随着循环从一列到另一列而变化。 I'm just not sure how to format "=B2+C3" to achieve this. 我只是不确定如何格式化"=B2+C3"来实现这一点。 I'm open to any other more efficient looping process or way to make any part of the code more efficient. 我愿意接受任何其他更有效的循环过程或使代码的任何部分更有效的方法。 Also, I'm not sure if " Loop Until LasCol " is a valid end to the loop. 另外,我不确定“ Loop Until LasCol ”是否有效。 Any help is much appreciated. 任何帮助深表感谢。

Regards, 问候,

I'm not sure why you are incrementing Row but your loop's condition is based on Column . 我不确定为什么要增加Row,但是循环的条件是基于Column的 I've made some assumptions with the following. 我对以下内容进行了一些假设。

Sub LoopAcrossCols()
    Dim c As Long, lc As Long
    With Sheets("Sheet1")
        lc = .Cells(1, Columns.Count).End(xlToLeft).Column
        For c = 3 To lc
            .Cells(2, c).FormulaR1C1 = "=SUM(RC[-1], R[1]C)"
        Next c
    End With
End Sub

Alternate method of filling range with formula without loop. 不带公式的填充范围的替代方法。

Sub LoopAcrossCols2()
    Dim lc As Long
    With Sheets("Sheet1")
        lc = .Cells(1, Columns.Count).End(xlToLeft).Column
        .Cells(2, 3).Resize(1, lc - 2).FormulaR1C1 = "=SUM(RC[-1], R[1]C)"
    End With
End Sub

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

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