VBA 自动得到分数

 

' 将一个正数除以 y 返回一个整数或分数
Function RFs(ByVal x As Integer) As String
    If x = 0 Then
        RFs = 0
        Exit Function
    End If

    Dim div_result, div_remain, y, i As Integer
    y = 144
    div_result = x \ y
    div_remain = x Mod y
    
    If div_remain = 0 Then
        RFs = x / y
        Exit Function
    Else
        Dim z As Integer
        If div_remain > y Then
            z = y
        Else
            z = div_remain
        End If
        
        For i = z To 2 Step -1
            If div_remain Mod i = 0 And y Mod i = 0 Then
                If div_result > 0 Then
                    RFs = div_result & " + " & div_remain / i & "/" & y / i
                Else
                    RFs = div_remain / i & "/" & y / i
                End If
                Exit Function
            End If
        Next i
        If div_result > 0 Then
            RFs = div_result & " + " & div_remain & "/" & y
        Else
            RFs = div_remain & "/" & y
        End If
    End If
End Function

 

可以直接在 Excel 宏里面用 VBA 语言调用 比如 290 会得到 2 + 1/72

posted on 2015-04-09 09:13  z5337  阅读(452)  评论(1编辑  收藏  举报