通过有效数字的规则四舍五入

时间:2014-01-29 02:02:08

标签: excel-vba vba excel

有没有办法将有效数字的规则应用于Excel工作表,即从宏中打印值?

或者以任何方式,VBA宏计算的值都会通过有效数字规则而不是打印在excel表上?

2 个答案:

答案 0 :(得分:2)

以下是有效数字的公式:

=ROUND(REFERENCE,SIGFIGS-1-INT(LOG10(ABS(REFERENCE))))

例如,如果您希望A1中的值为3位有效数字,则可以输入:

=ROUND(A1,2-INT(LOG10(ABS(A1))))

编辑:如果你愿意的话,我只是把一个快速的VBA宏汇集到一个选择中的每个单元格中:

Sub ConvertToSigfigs()
    Dim Sigfigs As Integer
    Sigfigs = 3 'Change this to whatever value you want
    Dim cel As Range
    For Each cel In Selection
        cel.Value = Application.WorksheetFunction.Round(cel.Value, Sigfigs - 1 - Int(Application.WorksheetFunction.Log10(Abs(cel.Value))))
    Next
End Sub

注意我使用了Application.WorksheetFunction.Round()而不是VBA的Round(),所以它可以使用非十进制数字。

编辑2:这是一个UDF:

Function Sigfig(Inpt As Double, Precision As Integer) As Double
    Sigfig = Application.WorksheetFunction.Round(Inpt, Precision - 1 - Int(Application.WorksheetFunction.Log10(Abs(Inpt))))
End Function

编辑3:这不会做的一件事是保留终端零,例如如果你有4.0001并且舍入到三个sig figs,excel将显示4,而不是4.00。如果绝对需要,可以根据模数在子中添加格式。

一个简洁的项目是使用UDF,然后有一个sub来解析UDF,然后将其转换为Excel公式,这样你就不必另存为.xlam。

答案 1 :(得分:0)

我一直在研究一个VBA用户定义函数,用有效数字或有限数量的小数进行科学舍入,这就是我在宏中使用的组合。

要在'= SciRound(B3,3)'等工作表上使用,请按Alt + F11打开Visual Basic编辑器,然后从插入菜单中添加一个模块。将代码复制/粘贴到Module1中然后使用 比如'= SciRound(数字或单元格位置为圆形,SigFigs,小数位)'

Public Function SciRound(number, sigfigs, Optional decimals As Variant)
'      Nov2013 TP
Dim exp As Integer, n As Integer
Dim bdec As Boolean, test As Variant

If (IsEmpty(number) Or IsMissing(number)) = True Then SciRound = CVErr(xlErrNull)
If IsNumeric(number) = False Then SciRound = CVErr(xlErrValue)

If (IsNumeric(sigfigs) = False) Or (sigfigs < 1) Then SciRound = CVErr(xlErrValue)

If (IsMissing(decimals) Or IsEmpty(decimals)) = True Then bdec = False Else bdec = True
If bdec = True Then
  If (IsNumeric(decimals) = False) Then SciRound = CVErr(xlErrValue)    
  If (Int(decimals) <> decimals) Then SciRound = CVErr(xlErrNum)
End If

If IsError(SciRound) = True Then Exit Function
If number = 0 Then SciRound = 0: Exit Function

number = CDec(number): test = Abs(number): n = 0
n = Int((Log(test) / Log(10#)))  '  natural log to log10
exp = (sigfigs - n) - 1

If bdec = True Then
 If (exp < decimals) Then bdec = False
End If
If bdec = True Then
 SciRound = Round((number * 10 ^ decimals), 0) * 10 ^ -decimals
Else
 SciRound = Round((number * 10 ^ exp), 0) * 10 ^ -exp
End If
End Function
相关问题