Excel

Base to decimal conversion function

Ease of Use

Easy

Version tested with

2003 

Submitted by:

RichardSchollar

Description:

Provides a VBA function to convert a string representation of a number in the specified base (in the range base 2 to base 16) to its decimal equivalent. The function returns a long integer. 

Discussion:

This is the complementary function to the Dec2Base function here: http://vbaexpress.com/kb/getarticle.php?kb_id=949 The two together permit conversion from one base (base 2 to base 16) to any other base in this range. This extends the functionality provided by the Analysis Toolpak functions such as BIN2DEC and HEX2DEC. The outputted long decimal's maximum value is 2,147,483,647. 

Code:

instructions for use

			

Option Explicit Sub tester() 'testing sub - this code is NOT required to run the function - it only 'demonstrates the function in operation Dim s As String s = "500 in base..." & vbCr & "16 is " & Base2Dec("500", 16) & " in Decimal" & vbCr & _ "8 is " & Base2Dec("500", 8) & " in Decimal" & vbCr & _ "13 is " & Base2Dec("500", 13) & " in Decimal" MsgBox s End Sub Public Function Base2Dec(ByVal BaseVal As String, ByVal base As Long) As Variant 'converts a string representation of a number in base(base) to the equivalent in decimal '(base 2 to base 16). Base needs to be specified as decimal ie '8 for base 8, 16 for base 16, 2 for base 2 etc Static Digits Dim i As Long, sTemp As String, lVal As Long 'check valid base: If base < 2 Or base > 16 Then Base2Dec = "Invalid base used": Exit Function On Error GoTo err_handler If IsEmpty(Digits) Then _ Digits = VBA.Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F") sTemp = UCase(BaseVal) lVal = 0 'generate decimal values of BaseVal digits: For i = Len(BaseVal) To 1 Step -1 lVal = lVal + (WorksheetFunction.Match(Mid$(BaseVal, i, 1), Digits, False) - 1) * (base ^ (Len(BaseVal) - i)) Next i 'output: Base2Dec = lVal: Exit Function err_handler: Base2Dec = "Error" End Function

How to use:

  1. Copy the code to a standard module in a workbook. The function can then be called by other procedures within that workbook or used directly in the worksheets of the workbook. The second argument to the function is the base of the number representation provided in the first argument.
  2. eg in cell A1:
  3. =Base2Dec(85648,9)
 

Test the code:

  1. Copy the code in and run the 'tester' sub.
 

Sample File:

Base2Dec.zip 9.21KB 

Approved by mdmackillop


This entry has been viewed 106 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express