插入特定公式的函数excel VBA(小数到小数英寸)
我有一个距离的列表,我想显示,就像读取一个卷尺一样,例如144.125会显示为144 1/8“。我有下面的公式
=TEXT(A1,"0"&IF(ABS(A1-ROUND(A1,0))>1/32,"0/"&CHOOSE(ROUND(MOD(A1,1)*16,0),16,8,16,4,16,8,16,2,16,8,16,4,16,8,16),""))&""""
我想简化它为1参数函数(对于A1),所以我可以在整个工作簿中使用它,但quotes和vba关键字的数量造成的问题。是否有一个更简单的方法来获得UDF插入复杂的公式?
如果你想用Visual Basic来使用UDF
,那么试试这个:
Public Function Fraction(ByVal x As Double, Optional ByVal tol As Double = 1 / 64#) As String Dim s As Long, w As Long, d As Long, n As Long, f As Double s = Sgn(x): x = Abs(x) If s = 0 Then Fraction = "0" Exit Function End If w = CInt(WorksheetFunction.Floor_Precise(x)): f = x - w d = CInt(WorksheetFunction.Floor_Precise(1 / tol)): n = WorksheetFunction.Round(f * d, 0) Dim g As Long Do g = WorksheetFunction.Gcd(n, d) n = n / g d = d / g Loop While Abs(g) > 1 Fraction = Trim(IIf(s < 0, "-", vbNullString) + CStr(w) + IIf(n > 0, " " + CStr(n) + "/" + CStr(d), vbNullString)) End Function
结果:
TEXT函数可以直接做到这一点:
AB 1 144,1250 144 1/8 "
B1中的公式:
=TEXT(A1;"# ??/??\""")
问候
阿克塞尔