excel vba decimal to binary code example

Example: excel vba convert number to binary string

'VBA function to convert number to binary string:

Function DecToBin$(ByVal n&)
    Do
        DecToBin = n Mod 2 & DecToBin
        n = n \ 2
    Loop While n
End Function

'-------------------------------------------------------------------  
'NB: Excel has the built-in worksheet function, DEC2BIN(), but it
'can only handle 10-bit numbers or less. The above function can
'convert all positive 32-bit numbers: 
  
MsgBox DecToBin(9512489)    '<--displays: 100100010010011000101001

Tags:

Vb Example