Excel VBA 运行时错误 '424' 需要对象 将单元格内容替换为四舍五入到当前值的小数点后 2 位



我正在尝试将某些单元格的内容替换为当前相同数量的四舍五入。错误位于我定义 LastRow 变量的行上(在 With/End With 命令中(。奇怪的是,这段代码在几周前曾经工作正常。

这是我的代码:

Dim LastRow As Integer
'   Looks up the last row of data and assigns it to one of the variables on columns I and J
With ActiveWorksheet
LastRow = .Range("I" & .Rows.Count).End(xlUp).Row
End With
Set rng = Range("I2:J" & LastRow)
'   Replaces current contents of columns I and J with the same value but rounded to 2 decimals
For Each cell In rng
If cell = "" Then Exit Sub
cell.Value = WorksheetFunction.Round(cell.Value, 2)
Next cell

没有ActiveWorksheet这样的东西,只有ActiveSheet

ActiveWorksheet更改为ActiveSheet(并将Option Explicit添加到模块顶部(。

另请注意,应使用Long而不是Integer以避免潜在的Overflow错误。

最新更新