我创建了一个宏来执行各种计算。但是,在代码的这一部分,它表示行
中存在错误(需要对象)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
答案 0 :(得分:2)
这是一种方法:
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。