Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

XL2000: Visual Basic Macro to Convert Number to a Different Base


View products that this article applies to.

This article was previously published under Q213392

↑ Back to the top


Summary

This article contains a sample Microsoft Visual Basic for Applications function that converts an integer number to any base less than 10.

↑ Back to the top


More information

The following function is a sample function called "baseconv" that takes two arguments. The first argument, InputNum, is an integer number to be converted. The second argument, BaseNum, is the number of the base to convert InputNum to.

Sample Visual Basic Procedure

Function baseconv(InputNum, BaseNum)
   Dim quotient, remainder As Single
   Dim answer As String

   quotient = InputNum   ' Set quotient to number to convert.
   remainder = InputNum  ' Set remainder to number to convert.
   answer = ""

   Do While quotient <> 0   ' Loop while quotient is not zero.

      ' Store the remainder of the quotient divided by base number in a
      ' variable called remainder.

      remainder = quotient Mod BaseNum

      ' Reset quotient variable to the integer value of the quotient
      ' divided by base number.

      quotient = Int(quotient / BaseNum)

      ' Reset answer to contain remainder and the previous answer.
      answer = remainder & answer
      ' Convert answer variable to a number.
   Loop
      baseconv = Val(answer)
End Function
				
The function should be typed in a worksheet cell as follows:
   =baseconv(InputNum, BaseNum)
				
For example, the following call to the baseconv function
   =baseconv(100,2)
				
returns the following value in the cell:
   1100100
				

↑ Back to the top


References

For more information about creating function procedures in Microsoft Excel, click Microsoft Visual Basic Help on the Help menu, type Writing a Function Procedure in the Office Assistant or the Answer Wizard, and then click Search to view the topic.

To access Visual Basic Help:

  1. On the Tools menu, point to Macro, and then click Visual Basic Editor.
  2. On the Help menu, click Microsoft Visual Basic Help.

↑ Back to the top


Keywords: KB213392, kbprogramming, kbhowto, kbdtacode

↑ Back to the top

Article Info
Article ID : 213392
Revision : 6
Created on : 10/11/2006
Published on : 10/11/2006
Exists online : False
Views : 233