Excel

Convert any Decimal Number from 1 to 1.79769313486231E308 to Hex

Ease of Use

Intermediate

Version tested with

2002, 2003 

Submitted by:

Jacob Hilderbrand

Description:

This User Defined Function will convert a Decimal number to Hex. 

Discussion:

Excel's DEC2HEX Worksheet Function will convert Decimal numbers to Hex, but only up to 5x10^11. It cannot convert larger numbers. If you need to convert a number larger than 5x10^11 to Hex, then this macro is what you need. Refer to the KB Entry (http://www.vbaexpress.com/kb/getarticle.php?kb_id=307) to reverse this process. 

Code:

instructions for use

			

Option Explicit Public Function DecToHex(Dec As Double) As String Dim i As Long Dim n As Long Dim PlaceValHex As Long Dim Hex(1 To 256) As String Dim HexTemp As String Dim Divisor As Long Dec = Int(Dec) For i = 256 To 2 Step -1 If Dec >= 16 ^ (i - 1) And Dec > 15 Then PlaceValHex = Int(Dec / (16 ^ (i - 1))) Dec = Dec - (16 ^ (i - 1)) * PlaceValHex Select Case PlaceValHex Case 0 To 9 Hex(i) = CStr(PlaceValHex) Case Is = 10 Hex(i) = "A" Case Is = 11 Hex(i) = "B" Case Is = 12 Hex(i) = "C" Case Is = 13 Hex(i) = "D" Case Is = 14 Hex(i) = "E" Case Is = 15 Hex(i) = "F" End Select Else Hex(i) = "0" End If Next i PlaceValHex = Dec Select Case PlaceValHex Case 0 To 9 Hex(1) = CStr(PlaceValHex) Case Is = 10 Hex(1) = "A" Case Is = 11 Hex(1) = "B" Case Is = 12 Hex(1) = "C" Case Is = 13 Hex(1) = "D" Case Is = 14 Hex(1) = "E" Case Is = 15 Hex(1) = "F" End Select For i = 256 To 1 Step -1 If Hex(i) = "0" Then Else n = i Exit For End If Next i For i = n To 1 Step -1 HexTemp = HexTemp & Hex(i) Next i DecToHex = HexTemp End Function

How to use:

  1. Open Excel.
  2. Alt + F11 to open the VBE.
  3. Insert | Module.
  4. Paste the code from above in the Code Window that opens up.
  5. Close the VBE (Alt + Q or press the X in the top right corner).
 

Test the code:

  1. Option 1: In a worksheet cell input = DecToHex(#).
  2. Option 2: In a VBA macro input MyNum = DecToHex(#).
  3. Just replace # with your number.
 

Sample File:

DecToHex.ZIP 8.17KB 

Approved by mdmackillop


This entry has been viewed 103 times.

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