Search code examples
exceloffsetvba

Excel VBA offset property (NOT function)


I have an Excel file with information in column A and column B. Since these columns could vary in the number of rows I would like to use the function offset so that I could print the formula in one time as an array rather than looping over the formula per cell (the dataset contains almost 1 million datapoints).

My data is as follow:

My code is actually working the way I want it to be I only can't figure out how to print the code in Range(D1:D5). The outcome is now printed in Range(D1:H1). Anybody familiar how to use this offset within a for statement?

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

Solution

  • Using the Offset(Row, Column) PROPERTY, you want to offset with the increment of row (i -1), and 3 columns to the right (from column "A" to column "D")

    Try the modified code below:

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