我有一组不固定的数据,可能在行和列中有所不同。
我打算使用VBA搜索整个数据集,并将所有带有数字的单元格四舍五入到指定的小数位。 (或也舍入到最接近的100s或10s)
我有以下代码:
Sub roundthissheet()
Dim cell As Range, rng As Range
rng = Range("A1", ActiveCell.SpecialCells(xlLastCell)).Select
For Each cell In rng.cells
If cell.Value <> "" And IsNumeric(cell.Value) Then
cell.Value = Round(cell.Value, -2)
End If
Next cell
End Sub
但是,我的if语句似乎根本没有运行,并且遇到错误消息“未设置对象变量或With块变量”
我应该如何处理此错误?
答案 0 :(得分:1)
如果您只想设置数字格式,请尝试
Sub Sample()
Dim ws As Worksheet
Dim rng As Range
Set ws = Sheet1 '<~~ Change this to the relevant sheet
With ws
On Error Resume Next
Set rng = .Cells.SpecialCells(xlCellTypeConstants, 1)
On Error GoTo 0
If Not rng Is Nothing Then rng.NumberFormat = "0.00"
End With
End Sub
如果要四舍五入,则不需要遍历所有单元格。使用SpecialCells
仅遍历具有数字的单元格
Sub Sample()
Dim ws As Worksheet
Dim rng As Range, aCell As Range
Set ws = Sheet1 '<~~ Change this to the relevant sheet
With ws
On Error Resume Next
Set rng = .Cells.SpecialCells(xlCellTypeConstants, 1)
On Error GoTo 0
If Not rng Is Nothing Then
For Each aCell In rng
aCell.Value = Round(aCell.Value, 2)
Next
End If
End With
End Sub
答案 1 :(得分:1)
如果要设置范围,则需要SET
命令,并且在设置时不要.Select
:
rng = Range("A1", ActiveCell.SpecialCells(xlLastCell)).Select
成为:
Set rng = Range("A1", ActiveCell.SpecialCells(xlLastCell))
此外,在四舍五入时,您还指定了一个负值。
cell.Value = Round(cell.Value, -2)
成为:
cell.Value = Round(cell.Value, 2)
所以代码最终如下:
Sub roundthissheet()
Dim cell As Range, rng As Range
Set rng = Range("A1", ActiveCell.SpecialCells(xlLastCell))
For Each cell In rng.Cells
If cell.Value <> "" And IsNumeric(cell.Value) Then
cell.Value = Round(cell.Value, 2)
End If
Next cell
End Sub
答案 2 :(得分:0)
你可以的。
Sub RoundValues()
Dim cel As Range, rng As Range
Set rng = Range("A1", Range("A1").End(xlDown).Address)
For Each cel In rng
If cel.Value <> "" And IsNumeric(cel.Value) Then
cel.Value = Round(cel.Value2, 2)
End If
Next cel
End Sub