excelvba greatest common denominator code example

Example: excel vba greatest common denominator

'VBA function to find the Greatest Common Denominator of two numbers:

Function GCD(ByVal a, ByVal b)      '<--Euclid's algorithm
    a = Abs(a): b = Abs(b)
    While b
        If a > b Then a = a - b Else b = b - a
    Wend
    GCD = a
End Function
    
'------------------------------------------------------------------------------
    
MsgBox GCD(15, 20)          '<--displays: 5
    
    
'Note: the GCD() worksheet function is also available but requires the 
'slow call to the worksheet calcuation engine:
      
MsgBox WorksheetFunction.GCD(15, 20)

Tags:

Vb Example