gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:40:45 25 4
gpt4 key购买 nike

细胞是:

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使用 xlCellType Enumeration 中的 xlCellTypeConstants 和 xlCellTypeFormulas 选项. .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到,您应该大大缩短循环通过工作表中的单元格的迭代。

关于excel - 如何在每个选择单元格中添加 ROUND(),但是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34159016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com