[英]Function to insert a specific formula excel VBA (decimal to fractional inches)
我有一個要顯示的距離列表,就像您讀一個卷尺一樣,例如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),以便可以在整個工作簿中使用它,但是引號和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函數可以直接執行此操作:
A B
1 144,1250 144 1/8 "
B1中的公式:
=TEXT(A1;"# ??/??\""")
問候
阿克塞爾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.