vba 中偏移量的计算错误
Error with calculations with offsets in vba
我创建了一个宏来执行各种计算。但是,在这部分代码中,它表示
行中存在错误(需要对象)
cell2.Value = cell2.Offset(0, -2).Value * cell2.Offset(0, -1).Value
我提供了该行所属的全部代码:
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
这是一种方法:
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
在 excel 中构建一些公式并使用宏记录器查看它们如何转换为 VBA。
我创建了一个宏来执行各种计算。但是,在这部分代码中,它表示
行中存在错误(需要对象)cell2.Value = cell2.Offset(0, -2).Value * cell2.Offset(0, -1).Value
我提供了该行所属的全部代码:
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
这是一种方法:
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
在 excel 中构建一些公式并使用宏记录器查看它们如何转换为 VBA。