【问题标题】:Excel VBA offset functionExcel VBA 偏移函数
【发布时间】:2018-01-17 17:42:03
【问题描述】:

我有一个 Excel 文件,其中包含 A 列和 B 列中的信息。由于这些列的行数可能不同,我想使用函数 offset 以便我可以在一次作为数组而不是循环遍历每个单元格的公式(数据集包含近 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

【问题讨论】:

    标签: excel offset vba


    【解决方案1】:

    使用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
    

    【讨论】:

      【解决方案2】:

      在一个步骤中将公式输出到整个范围而不循环的一种方法是使用 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
      

      【讨论】:

        【解决方案3】:
        1. 您不需要为此使用 VBA。只需在单元格 D1 中输入 =sum(A1:B1),然后输入 fill it down

        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 处。

        【讨论】:

        • 是的,我明白这一点,但由于它最终将用于我正在构建的更大的工具中,我希望一切都由 vba 计算。
        猜你喜欢
        • 2017-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-15
        相关资源
        最近更新 更多