细胞是:
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
谢谢Jeeped:)
答案 0 :(得分:1)
这个短子使用来自Range.SpecialCells method的xlCellTypeConstants和xlCellTypeFormulas选项的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中的公式或常量,您可能希望提供一些错误控制。如果没有找到,那么.SpecialCells将返回nothing
。
只关注那些可能具有数值的单元格来应用ROUND function,你应该大大缩短循环遍历工作表中单元格的迭代次数。