Search code examples
vbaexcelexcel-formulaoffset

Error with calculations with offsets in vba


I have created a macro to perform various calculations. However, at this part of the code, it says there is an error(object required) in the line

cell2.Value = cell2.Offset(0, -2).Value * cell2.Offset(0, -1).Value

I am providing the entire part of the code where this line belongs to:

For Each cell2 In Range("F2:F" & lastrow2)
If cell2.Offset(0, -3).Value = "ROMANIA" Then
cell2.Value = cell2.Offset(0, -2).Value / cell2.Offset(0, -1).Value
Else
cell2.Value = cell2.Offset(0, -2).Value * cell2.Offset(0, -1).Value
End If
Next cell2

Solution

  • This is a way to do it:

    Option Explicit
    
    Public Sub TestMe()
    
        Dim cell2       As Range
        Dim lastrow2    As Long
        Dim wks         As Worksheet
    
        lastrow2 = 55 'or calculated value
    
        Set wks = Worksheets("SomeName")
    
        For Each cell2 In wks.Range("F2:F" & lastrow2)
            If cell2.Offset(0, -3).Value = "ROMANIA" Then
                cell2.FormulaR1C1 = "=RC[-2]/RC[-1]"
                'cell2.Formula = cell2.Offset(0, -2).Value / cell2.Offset(0, -1).Value
            Else
                cell2.FormulaR1C1 = "=RC[-2] * RC[-1]"
                'cell2.Formula = cell2.Offset(0, -2).Value * cell2.Offset(0, -1).Value
            End If
        Next cell2
    
    End Sub
    

    Build a few formulas in excel and use the macro recorder to see how they are translated to VBA.