Sub autoaddround()
'适用于空值,数值和公式,自动保留小数
Dim a As Integer
Dim mycell As Range, b As String, d As String, c As String
a = InputBox("保留几位小数")
For Each mycell In Selection
mycell.Select
b = ActiveCell.Formula
d = Left(b, 1)
If ActiveCell.Value <> "" Then '当单元格非空时运算
If d = "=" Then '当单元格是公式
c = Right(b, Len(b) - 1)
ActiveCell.Formula = "=round(" & c & "," & a & ")"
ElseIf TypeName(ActiveCell.Value) <> "String" Then '当单元格非字符,也就是数字
ActiveCell.Formula = "=round(" & b & "," & a & ")"
End If
End If
Next
End Sub
Sub unround()
'取消自动保留小数的公式
Dim mycell As Range
Dim b As String
Dim c As Integer
For Each mycell In Selection
mycell.Select
b = ActiveCell.Formula
If Left(b, 6) = "=ROUND" Then
c = Application.WorksheetFunction.Find(",", b, Len(b) - 4)
ActiveCell.Formula = "=" & Mid(b, 8, c - 8)
End If
Next
End Sub
Sub errortozero()
'当单元格为公式时,才取0,数值则不行
Dim a As Integer
Dim mycell As Range
a = MsgBox("值错误取0。值正确,选Yes,取原值;选No,取1", vbYesNoCancel, "错误值取0")
If a <> 2 Then '当选cancel时,不运行
For Each mycell In Selection
mycell.Select
b = ActiveCell.Formula
d = Left(b, 1)
If a = 6 Then '当选yes时
If ActiveCell.Value <> "" Then
If d = "=" Then
c = Right(b, Len(b) - 1)
ActiveCell.Formula = "=if(iserror(" & c & "),0," & c & ")"
End If
End If
ElseIf a = 7 Then '当选no时
If ActiveCell.Value <> "" Then
If d = "=" Then
c = Right(b, Len(b) - 1)
ActiveCell.Formula = "=if(iserror(" & c & "),0,1)"