如何在选择的每个单元格中添加 ROUND(),但是

How to add ROUND() in every cell of selection, but

单元格是:

3.141516
=10/6
=rand()
or blank
etc...

结果:

=ROUND(3.141516,1)
=ROUND(10/6,1)
=ROUND(RAND(),1)

如果为空 - 留空(不是 ROUND(,1) )

我想通过 InputBox 或其他方式选择范围和小数点

我找到了如何在公式周围、常量周围、空白单元格、输入框周围添加 ROUND(),但所有这些都在单独的代码中,而不是在一起。我不是 vba 英雄,所以我需要帮助。谢谢:)

Sub RoundNum()
Dim Rng As Range
Dim WorkRng As Range
Dim xNum As Integer
On Error Resume Next
xTitleId = "Round Numbers"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
xNum = Application.InputBox("Decimal", xTitleId, Type:=1)
For Each Rng In WorkRng
    Rng.Value = Application.WorksheetFunction.Round(Rng.Value, xNum)
Next
End Sub
Sub Makro1()
Dim Str As String
For Each cell In Selection
Str = cell.FormulaR1C1
If Mid(Str, 1, 1) = "=" Then Str = Mid(Str, 2)
cell.FormulaR1C1 = "=ROUND(" & Str & ",1)"
Next cell
End Sub

最后我做了这样的事情:

Sub rRoundIt()
Dim rng As Range
Dim rngArea As Range
Dim AppCalc As Long
On Error Resume Next
With Application
    AppCalc = .Calculation
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
End With
Set rng = Union(Selection.SpecialCells(xlCellTypeFormulas, xlNumbers), _
                Selection.SpecialCells(xlCellTypeConstants, xlNumbers))
For Each rngArea In rng
    If Left(rngArea.Formula, 7) <> "=ROUND(" Then _
        rngArea.Formula = "=ROUND(" & Replace(rngArea.Formula, Chr(61), vbNullString) & ", 1)"
Next rngArea
With Application
    .ScreenUpdating = True
    .Calculation = AppCalc
End With
End Sub

谢谢吉普车:)

这个短子利用了 Range.SpecialCells method using both the xlCellTypeConstants and xlCellTypeFormulas options from xlCellType Enumeration。 .SpecialCells 通过仅获取那些使用 xlNumbers 选项生成数字的常量或公式来进一步过滤。

Sub roundIt()
    Dim r As Range, rng As Range
    With Worksheets("Sheet1")
        With .UsedRange.Cells
            Set rng = Union(.SpecialCells(xlCellTypeFormulas, xlNumbers), _
                            .SpecialCells(xlCellTypeConstants, xlNumbers))
            For Each r In rng
                If Left(r.Formula, 7) <> "=ROUND(" Then _
                    r.Formula = "=ROUND(" & Replace(r.Formula, Chr(61), vbNullString) & ", 1)"
            Next r
        End With
    End With
End Sub

理想情况下,如果工作表 .UsedRange property 中没有代表数字的公式或常量,您可能希望提供一些错误控制。如果要找到 none,那么 .SpecialCells 将 return nothing.

通过只关注那些可能具有数值以应用 ROUND function 的单元格,您应该大大缩短循环遍历工作表中单元格的迭代次数。