2014-01-29 26 views
1

有什麼辦法將有效數字的規則應用於Excel工作表,即從宏打印值?舍入通過有效數字的規則

或者以任何方式,由VBA宏計算出的值經過重要的數字規則並且不會打印在Excel表格上?

回答

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和三舍入無花果,excel將顯示4,而不是4.00。如果這是絕對需要的話,可以在子模塊中添加基於模塊的格式。

一個整潔的項目將使用UDF,然後有一個子解析UDF後將其轉換爲Excel公式,因此您不必另存爲.xlam。

0

我一直在研究一個VBA用戶定義的函數來進行科學舍入與有效數字或有限數量的小數,這是我在一起使用宏。

要在'= SciRound(B3,3)'等工作表上使用,請按Alt + F11打開Visual Basic編輯器,然後從插入菜單中添加一個模塊。複製/粘貼代碼到Module然後使用 像「= 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