Excel VBA偏移function

我有一个Excel文件的列A和列B中的信息。由于这些列可能会有所不同的行数我想要使用函数偏移,以便我可以一次打印公式作为一个数组,而不是循环遍历每个单元格的公式(该数据集包含近1百万个数据点)。

我的数据如下:

我的代码实际上是我想要的方式,我只是不知道如何打印范围(D1:D5)中的代码。 结果现在打印在范围(D1:H1)中。 任何人都熟悉如何在for语句中使用这个偏移量?

Sub checkOffset() Dim example As Range Dim sht As Worksheet Dim LastRow As Long Set sht = ThisWorkbook.Worksheets("Sheet1") LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row Set example = Range("A1:A1") For i = 1 To LastRow example.Offset(0, i + 2).Formula = "=SUM(A" & i & ":B" & i & ")" Next i End Sub 

使用Offset(Row, Column) ,您希望以行( i -1 )的增量和向右(从列“A”到列“D”)的3列进行偏移

尝试下面的修改后的代码:

 Set example = Range("A1") For i = 1 To LastRow example.Offset(i - 1, 3).Formula = "=SUM(A" & i & ":B" & i & ")" Next i 

将公式一步输出到整个范围的一种方法是使用R1C1表示法:

编辑:修改代码以正确限定工作表引用

 Option Explicit Sub checkOffset() Dim example As Range Dim sht As Worksheet Dim LastRow As Long Set sht = ThisWorkbook.Worksheets("Sheet1") With sht LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row Set example = .Range(.Cells(1, 1), .Cells(LastRow, 1)) End With example.Offset(columnoffset:=3).FormulaR1C1 = "=sum(rc[-3],rc[-2])" End Sub 
  1. 你不需要为此使用VBA。 只要在D1单元格中input= sum(A1:B1),然后填写它 。

  2. 如果你打算使用VBA,使用这个:

     Sub checkOffset() Dim example As Range Dim sht As Worksheet Dim LastRow As Long Set sht = ThisWorkbook.Worksheets("Sheet1") LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row Set example = Range("A1:A1") For i = 1 To LastRow example.Offset(i - 1, 3).Formula = "=SUM(A" & i & ":B" & i & ")" Next i End Sub 

offset工作方式是行偏移,列偏移。 您希望列始终固定在3的右侧。