Simplify Fraction UDF Error

Juggler_IN

Active Member
Joined
Nov 19, 2014
Messages
358
Office Version
  1. 2003 or older
Platform
  1. Windows
I have a Simply Fraction UDF which works fine whenever the numerator is less than the denominator, but fails other wise. For example for n = 50, d = 75 it outputs 2/3 but for n = 5 , d = 4 it is failing. Any reason?

Code:
Private Function reduceFraction(n As Integer, d As Integer)
    Dim numL As Variant
    Dim numR As Variant
    Dim i As Integer


    'check for both negative
    If n < 0 And d < 0 Then
        n = -1 * n: d = -1 * d
    End If
    'take out the whole number
    whole = Fix(n / d)


    'numL = IIf(whole > 0, Trim(whole) & " ", "")


    'set n to the remainder
    n = n Mod d
    MsgBox Abs(n)
    For i = Abs(n) To 2 Step -1
        If n / i = Fix(n / i) And d / i = Fix(d / i) Then
            numL = IIf(whole > 0, Trim(whole) & " ", "")
            'Debug.Print numL
            numR = Trim(n / i) & "/" & Trim(d / i)
            'Debug.Print numR
            reduceFraction = numL & numR
            Exit For
        End If
    Next i


End Function
 

Excel Facts

What is the shortcut key for Format Selection?
Ctrl+1 (the number one) will open the Format dialog for whatever is selected.
You might also consider the GCD function. You can come up with a more efficient function, such as:

Code:
Private Function ReduceFrac(n As Integer, d As Integer)
Dim g as Integer

    If n < 0 And d < 0 Then
        n = -n
        d = -d
    End If
    
    g = WorksheetFunction.Gcd(Abs(n), Abs(d))
    ReduceFrac = n / g & " / " & d / g
    
End Function
 
Last edited:
Upvote 0
Change this line

Code:
For i = Abs(n) To [SIZE=3][B][COLOR=#ff0000]1[/COLOR][/B][/SIZE] Step -1
 
Upvote 0

Forum statistics

Threads
1,224,737
Messages
6,180,665
Members
452,992
Latest member
TokugawaIesuma

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top