1

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
0

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

3

One way of outputting the formula in one step, without looping, to the entire range, is to use the R1C1 notation:

Edit: Code modified to properly qualify worksheet references

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

Comments

1
  1. You don't need to use VBA for this. Simply type =sum(A1:B1) in cell D1 and then fill it down.

  2. If you're going to use VBA anyway, use this:

    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
    

The way offset works is with row offset, column offset. You want the column to always be fixed at 3 to the right.

1 Comment

Yes I understand that, but since it will eventually be used in a larger tool that I am building I want everything to be calculated by vba.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.