我有一个 Excel 文件,其中包含 A 列和 B 列中的信息。由于这些列的行数可能不同,我想使用函数 偏移量 这样我就可以将公式一次性打印为数组,而不是循环遍历每个单元格的公式(数据集包含近 100 万个数据点)。
我的代码实际上按照我想要的方式工作我只是不知道如何在 Range(D1:D5) 中打印代码。结果现在打印在 Range(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
)和右边的 3 列(从“A”列到“D”列)偏移
试试下面的修改代码:
Set example = Range("A1")
For i = 1 To LastRow
example.Offset(i - 1, 3).Formula = "=SUM(A" & i & ":B" & i & ")"
Next i
关于Excel VBA 偏移函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45597356/