在工作表界面中按 <alt>+<F11>,
进入代码页面,然后再 WORKBOOK中插入模块,把以下代码COPY入模块中。
就可以在工作表中使用 =YXSZ(数值,保留位数)。
如:
A1=456.789
B1=YXSZ(A1,4)
=456.8
代码如下:
Public Function YXSZ(X, n As Integer) 'n为有效数字位数
Dim jk, j
Dim Y As Single
Dim temp As String
Dim zfh As Integer
zfh = 1
If X = "" Or (Not Application.WorksheetFunction.IsNumber(X)) Then mYX = "?Value!": Exit Function
X = Val(X)
If n < 1 Then mYX = X: Exit Function
If X <= 0 Then
zfh = -1
X = X * zfh
End If
If X < 1 Then
j = 1
Do
temp = CStr(X)
j = j + 1
Loop Until Val(Mid$(temp, j, 1)) > 0
j = j + n
X = X * 10 ^ j
jk = Len(CStr(Int(X))) - n
Y = X / 10 ^ jk + 0.5
YXSZ = Int(Y) * 10 ^ jk / 10 ^ j* zfh
X = X / 10 ^ j
Else
jk = Len(CStr(Int(X))) - n
Y = X / 10 ^ jk + 0.5
YXSZ = Int(Y) * 10 ^ jk * zfh
End If
End Function