Excel VBA Hex String: Convert Numbers to Hexadecimal

VBA & macros · Updated November 21, 2026

In Excel VBA, use the Hex function to turn a number into a hexadecimal string: Hex(255) returns FF. The result has no 0x or &H prefix and no automatic leading zeros, so formatting matters when you need a fixed-width byte or a string to write to a file.

What VBA’s Hex function returns

Hexadecimal is a base-16 number system. It uses the digits 0 through 9 and the letters A through F, where A represents 10 and F represents 15. Each hexadecimal digit represents four binary bits, making hex a compact way to display the bytes used in files, colors, device data, and other computer values.

In a standard VBA module, Hex(number) returns a string representation of the supplied number. For example, decimal 255 is hexadecimal FF, and decimal 16 is 10 in hexadecimal. The function reports the number’s value; it does not convert the text or characters in a cell into their byte encoding.

  • Hex(10) returns A.
  • Hex(16) returns 10.
  • Hex(255) returns FF.
  • Hex(4096) returns 1000.

The returned letters are uppercase. Hexadecimal is not case-sensitive, so ff and FF denote the same value, but consistent uppercase output is often convenient for logs and byte strings.

Using Hex in a VBA procedure

Put VBA code in a standard module in desktop Excel. On Windows, open the Visual Basic Editor with Alt+F11, then choose Insert > Module. On Mac, use Developer > Visual Basic or the Visual Basic Editor command available in the Tools menu; the keyboard shortcut can vary by keyboard. This small procedure writes a few results to the Immediate window, which you can display in the editor with Ctrl+G on Windows.

Public Sub ShowHexExamples()
    ' Print decimal values and their hexadecimal strings.
    Debug.Print Hex(10)       ' A
    Debug.Print Hex(255)      ' FF
    Debug.Print Hex(4096)     ' 1000
End Sub

These are VBA statements, not worksheet formulas. Save a copy of the workbook before running a macro: macro actions cannot be undone with Ctrl+Z. The Immediate window example only prints results, but the same function can be used when building a string, checking a value, or preparing output for a file.

Adding leading zeros and formatting bytes

Hex returns the shortest representation needed for the value. That is correct for a number, but byte data is normally written as two hex characters per byte. Without padding, the values 10 and 15 become A and F, which makes it difficult to tell where one byte ends and the next begins. Add a zero when a byte needs just one digit.

With a numeric value in the range 0 to 255, this expression produces a two-character byte string: Right$("0" & Hex(value), 2). For example, 10 becomes 0A, 15 becomes 0F, and 255 stays FF. Validate the range rather than silently allowing a negative value or a value above 255 to be treated as one byte.

Public Function ByteToHex(ByVal value As Long) As String
    ' Return exactly two hex characters for a single byte.
    If value < 0 Or value > 255 Then
        Err.Raise vbObjectError + 513, "ByteToHex", _
                  "Value must be from 0 to 255."
    End If

    ByteToHex = Right$("0" & Hex(value), 2)
End Function

Put this function in a standard module. In a worksheet, if the function is available in the workbook, enter =ByteToHex(A2) in a cell where A2 contains a whole number from 0 to 255. This is a user-defined VBA function, not a built-in Excel function. A workbook using VBA code needs a macro-enabled format such as .xlsm, and users must allow macros for the function to run. Excel for the web does not run VBA macros; use desktop Excel for this code.

For a multi-byte value, choose the width based on the data format. For example, an unsigned 16-bit value is commonly represented with four hex characters, so 255 would be 00FF. A simple width-four expression is Right$("0000" & Hex(value), 4), provided the value is in the appropriate range. Padding changes the display string; it does not change the numeric value.

Negative numbers and signed values

Negative inputs need special care because their hex output represents a signed integer using a two’s-complement form, not a minus sign followed by the positive magnitude. In VBA, Hex(-1) returns FFFFFFFF, and Hex(-2) returns FFFFFFFE. These eight characters correspond to a 32-bit representation. They should not be mistaken for an ordinary unsigned value that fits in a single byte.

If the intended output is a byte, first define what negative input means for the application. It may be invalid, or it may need to be deliberately mapped into the byte range according to a documented data format. Do not simply take the last two hex characters unless that wraparound behavior is explicitly intended. Similarly, a signed 32-bit value and an unsigned 32-bit value can share the same eight hex digits while representing different decimal values.

Converting a hexadecimal string back to a number

VBA uses the &H prefix for hexadecimal numeric literals, so a small value can be converted with an expression such as CLng(&HFF), which evaluates to 255. When the hex value is stored as text, a common pattern is to concatenate the prefix and pass the result to a conversion function. However, signed VBA integer types have limits: treating FFFFFFFF as an ordinary positive Long exceeds the signed 32-bit maximum. Know whether the text represents a signed or unsigned value before choosing a conversion method.

For an unsigned 32-bit value, the following function validates up to eight hexadecimal digits and accumulates the value in a Double. Every integer through 4,294,967,295 is represented exactly by a Double, so this is suitable for that range. It accepts an optional VBA-style &H prefix, but not a 0x prefix.

Public Function HexToUnsigned32(ByVal hexText As String) As Double
    Dim i As Long
    Dim digitValue As Long
    Dim result As Double
    Dim ch As String
    Dim digits As String

    ' Accept an optional VBA-style prefix and normalize the text.
    digits = UCase$(Trim$(hexText))
    If Left$(digits, 2) = "&H" Then digits = Mid$(digits, 3)
    If Len(digits) = 0 Or Len(digits) > 8 Then
        Err.Raise vbObjectError + 514, "HexToUnsigned32", _
                  "Enter one to eight hexadecimal digits."
    End If

    ' Convert each digit and reject characters outside 0-9 and A-F.
    For i = 1 To Len(digits)
        ch = Mid$(digits, i, 1)
        digitValue = InStr(1, "0123456789ABCDEF", ch, vbBinaryCompare) - 1
        If digitValue < 0 Then
            Err.Raise vbObjectError + 515, "HexToUnsigned32", _
                      "The text contains a non-hexadecimal character."
        End If
        result = result * 16 + digitValue
    Next i

    HexToUnsigned32 = result
End Function

For example, passing FFFFFFFF returns 4,294,967,295. If that same bit pattern is meant to be a signed 32-bit number, its signed value is -1; for values at or above 2,147,483,648, subtract 4,294,967,296 to obtain the signed interpretation. This distinction matters when reading binary formats or data from another application.

Hex strings are not text encodings

A frequent misconception is that Hex(65) converts the letter A into its hex character code. It does not convert text: it takes the number 65 and returns the hexadecimal representation of that number, 41. If a cell contains the text A, passing its contents to a numeric function is a different operation and may produce a type mismatch. Character encoding adds another layer: a character’s stored bytes depend on the encoding, and some characters use more than one byte.

To represent a text string as hexadecimal bytes, a program must first encode the text using a specified character encoding, then format each resulting byte. Choosing that encoding is essential for non-ASCII characters such as accented letters or symbols. A VBA routine that simply applies Asc or AscW to characters is not automatically a general UTF-8 byte encoder, so do not treat character codes as interchangeable with encoded file bytes.

Writing results to worksheet cells

Hex strings may look like numbers to Excel, particularly when a string contains only digits. To preserve the result as text, set the destination cell’s number format to Text before writing, or assign a leading apostrophe when entering a value interactively. A VBA assignment to a cell’s Value2 can write a string, but formatting the destination as text is a clear way to signal that strings such as 000A must retain their leading zeros.

For example, a macro can write a byte string after setting the cell format:

Public Sub WriteByteAsHex()
    Dim target As Range
    Dim value As Long

    ' Save a copy before running any macro that changes a workbook.
    Set target = ThisWorkbook.Worksheets("Sheet1").Range("B2")
    value = 10
    target.NumberFormat = "@"
    target.Value2 = ByteToHex(value)
End Sub

Change the worksheet name and destination to match the workbook. Before running a macro that modifies cells, save a copy; Ctrl+Z cannot undo VBA changes. If data is being exported, also decide whether the receiving system expects uppercase or lowercase hex, a prefix, spaces between bytes, or a continuous string. Those are conventions, not changes to the underlying value.

VBA Hex versus Excel’s worksheet functions

Use Hex in VBA code. If you need a worksheet formula rather than VBA, Excel has the DEC2HEX function for converting a decimal number to hexadecimal text; it also supports an optional character-width argument for leading zeros. The two approaches serve different contexts: Hex is a VBA function, while DEC2HEX is entered in a cell. Check the function’s supported input range and the desired signed or unsigned interpretation before relying on either for large values.

Another important difference is that ordinary cell formatting does not turn a decimal number into a hexadecimal string. A custom number format changes how a value is displayed, but it is not a general-purpose base conversion. If the result must be text for a file, a formula result or VBA string is usually a more explicit choice than visual formatting.

Common problems to check

  • Missing leading zeros: expected behavior for Hex; pad to the required width.
  • Overflow on a large value: check whether the number is unsigned and whether a signed VBA type can hold it.
  • Unexpected negative output: distinguish two’s-complement representation from a negative sign and magnitude.
  • Type mismatch: confirm that the input is numeric; text containing letters is not itself a number to Hex.
  • Zeros disappear in a cell: store the result as text and check the cell’s number format.
  • Macro or function does not run: use desktop Excel, place the code in a standard module, save in a macro-enabled format, and review the workbook’s macro security settings.

Frequently Asked Questions

What does Hex(255) return in Excel VBA?
Hex(255) returns the string FF. It does not include a prefix or leading zeros.

How do I make a two-digit hex string in VBA?
For a validated value from 0 to 255, use Right$("0" & Hex(value), 2). This returns 0A for 10 and FF for 255.

Does VBA Hex convert letters to ASCII or UTF-8?
No. Hex converts a numeric value to base-16 text. Turning text into encoded bytes requires selecting an encoding and converting the text to bytes first.

Can I use VBA Hex directly in a worksheet formula?
No. Hex is a VBA function, not a built-in worksheet function. You can write a VBA user-defined function in a standard module, or use Excel’s worksheet function DEC2HEX for a cell formula.

Why does Hex(-1) return FFFFFFFF?
VBA represents negative integer values in two’s-complement form. For a 32-bit signed value, -1 has the bit pattern of eight hexadecimal Fs; this is not a one-byte output.

Can Excel for the web run a VBA hex function?
No. Excel for the web does not run VBA macros or VBA user-defined functions. Open the macro-enabled workbook in desktop Excel to use them.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.