In Excel VBA, use the Hex function to turn a number into its hexadecimal text representation: for example, Hex(255) returns FF. It is a VBA function, not an Excel worksheet formula; for worksheet cells, use Excel’s DEC2HEX function or create a VBA user-defined function.
What VBA Hex Does
Hexadecimal, often called hex, is a base-16 number system. It uses the digits 0 through 9 and the letters A through F, where A represents 10, B represents 11, and F represents 15. Each hex digit corresponds to four binary bits, which makes hex a compact way to display values used in computing, colors, and data formats.
VBA’s Hex function accepts a numeric expression and returns a string. The result uses uppercase letters and has no prefix such as 0x or &H. It also does not preserve leading zeros: the decimal value 15 becomes F, not 0F. That is usually convenient for displaying a number, but it matters when a fixed-width code or identifier is required.
For example, decimal 255 is FF in hexadecimal because 15 × 16 + 15 = 255. Decimal 256 is 100, since it is one group of 16 squared. These are representations of the same numeric values, not different values that Excel can automatically treat as interchangeable text.
Syntax, Rounding, and Return Values
The syntax is Hex(number), where number is a numeric expression. The result is a string containing the hexadecimal representation. If the supplied numeric value is not a whole number, VBA rounds it to a whole number before converting it. For instance, a value of 10.4 rounds to 10 and produces A; 10.6 rounds to 11 and produces B. If rounding would be inappropriate for your task, convert or validate the value yourself before calling Hex.
Here are useful examples and their results:
Hex(0)returns0.Hex(10)returnsA.Hex(16)returns10.Hex(255)returnsFF.Hex(4095)returnsFFF.
Keep the return type in mind: the function returns text, even though the input is numeric. To calculate with the result, convert it back to a number with an appropriate conversion method rather than assuming the text itself is decimal.
Run Hex in a VBA Module
In Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor. Choose Insert > Module, then enter a procedure such as the following. The Debug.Print line sends the result to the Immediate window, which you can show in the editor with Ctrl+G.
Option Explicit
Public Sub ShowHexExample()
Dim value As Long
Dim hexText As String
' Convert decimal 255 and display its hexadecimal text.
value = 255
hexText = Hex(value)
Debug.Print hexText
End Sub
Run the procedure from the editor with the cursor inside it and press F5, or return to Excel and run it from Developer > Macros. The Immediate window displays FF. On a Mac, VBA is available in desktop Excel, but keyboard shortcuts can depend on the keyboard and system settings; use the Tools > Macro > Visual Basic Editor menu if the Windows shortcut does not apply. Excel for the web does not run VBA macros.
Save a copy of the workbook before running a macro that changes data. Macro actions cannot be reversed with Ctrl+Z, and saving a workbook containing VBA generally requires the macro-enabled .xlsm format. A procedure that only prints a result does not change worksheet cells, but making a backup is a sensible habit before running unfamiliar code.
Use Hex from a Worksheet Cell
VBA functions do not normally appear as worksheet functions just because they exist in a module. If the goal is a formula in a cell, Excel already provides DEC2HEX for converting a decimal number to hexadecimal. With the decimal number 255 in A2, enter =DEC2HEX(A2) in B2; the result is FF. The optional second argument sets a minimum number of characters: with 255 in A2, =DEC2HEX(A2, 4) returns 00FF. The cell layout assumed here is A2 containing the decimal input and B2 containing the formula.
To use your own VBA function in a cell, add a public function to a standard module:
Option Explicit
Public Function DecimalToHex(ByVal value As Long) As String
Dim result As String
' Return the hexadecimal text for a 32-bit Long value.
result = Hex(value)
DecimalToHex = result
End Function
With 255 in A2, type =DecimalToHex(A2) in B2; it returns FF. This example assumes A2 holds a value that fits in a VBA Long. Save the workbook as .xlsm, enable macros only when you trust the file, and keep the workbook open when using the function. A VBA user-defined function is not available in Excel for the web, and another workbook may not be able to use it unless the workbook or add-in containing the code is loaded.
Leading Zeros and Fixed-Width Values
Hex output is usually as short as possible. That is correct for a number, but a protocol, file format, color component, or identifier may require a fixed number of digits. For a nonnegative 32-bit Long value, the following VBA expression pads the output to eight characters:
Option Explicit
Public Function LongToEightHex(ByVal value As Long) As String
Dim hexText As String
' Pad a nonnegative value to eight hexadecimal characters.
hexText = Hex(value)
LongToEightHex = Right$("00000000" & hexText, 8)
End Function
For example, 255 becomes 000000FF. This is padding for display; it does not change the underlying number. The example is intentionally for nonnegative values. Negative numbers have signed representations, so padding them this way may conceal an assumption about the intended format. Decide the required width and signed-number convention before formatting data for another system.
Negative Numbers and VBA Data Types
A negative value does not have a simple positive-style hex spelling. Computers commonly represent signed integers using two’s complement, and VBA’s displayed result depends on the numeric value and type involved. A 32-bit Long, for example, has a different bit width from a 16-bit Integer. If you need a particular bit pattern, specify the input type and required width rather than treating a negative result as a universal text format.
VBA’s Long type ranges from -2,147,483,648 to 2,147,483,647. Values outside that range cannot be stored in a Long, so a function with a Long parameter is not suitable for every possible large integer. VBA also has wider numeric types in supported environments, but their availability and behavior can depend on the Office bitness and the declared type. For dependable interchange, document the width, signedness, and byte order expected by the receiving system.
Excel worksheet numbers also have finite precision. If a large integer has already been rounded when entered or calculated in a cell, converting that cell to hex cannot recover digits that Excel did not retain. For identifiers that must preserve every digit, consider storing them as text from the outset.
Hexadecimal Literals and the &H Prefix
VBA also lets you write a hexadecimal number directly in code by putting &H before its digits. For example, &HFF represents decimal 255. This is the reverse direction from calling Hex(255): the literal is a number in your code, while Hex(255) returns the text FF. Do not confuse VBA’s literal prefix with a prefix automatically included in the function’s result.
Hex literals are useful when a value is already documented in hexadecimal, such as a bit mask or a constant from a technical specification. They can make the intended bit pattern easier to recognize, but comments should clarify the meaning when the value is not self-explanatory. Also be careful with literals that set the highest bit of a signed integer: the interpretation can depend on the literal’s size and declared type.
Hex Values for RGB and HTML Colors
Color conversions are a common source of confusion. VBA’s RGB(red, green, blue) function returns a numeric color value, but simply applying Hex to that result does not necessarily produce the HTML color order #RRGGBB. Windows-style color values arrange the component bytes differently from the familiar HTML order. For example, VBA’s red value can appear as FF when converted directly, rather than the HTML string #FF0000.
To make an HTML-style color string, convert each channel separately and join the two-digit results in red, green, blue order:
Option Explicit
Public Function RGBToHtmlHex(ByVal red As Long, _
ByVal green As Long, _
ByVal blue As Long) As String
' Require each color channel to be in the byte range.
If red < 0 Or red > 255 Or _
green < 0 Or green > 255 Or _
blue < 0 Or blue > 255 Then
Err.Raise 5, "RGBToHtmlHex", "Color channels must be from 0 to 255."
End If
RGBToHtmlHex = "#" & _
Right$("0" & Hex(red), 2) & _
Right$("0" & Hex(green), 2) & _
Right$("0" & Hex(blue), 2)
End Function
With red 255, green 0, and blue 0, RGBToHtmlHex(255, 0, 0) returns #FF0000. Each component is padded to two digits so that zero becomes 00. The validation prevents values outside the valid 0–255 channel range from silently producing misleading output.
Common Problems and Safer Use
- The result has no leading zeros: This is normal. Add explicit padding only when a fixed-width representation is required.
- A worksheet cell shows a name error: A VBA function is not available if macros are disabled, the code is not in a standard module, or the workbook containing it is not open. Excel for the web cannot run VBA.
- A negative value looks unexpectedly long: Signed integer representations can show two’s-complement bits. Confirm the target width and signedness before interpreting the output.
- A color looks reversed: Do not convert the combined VBA
RGBnumber directly when you need an HTML color string. Convert the red, green, and blue channels separately. - A large value changes during conversion: Check the source cell’s precision and the VBA variable’s range. Hex conversion cannot restore precision lost earlier.
Macros can execute code and alter files, so do not enable them solely to obtain a conversion from an untrusted workbook. For a simple cell conversion, the built-in worksheet function may be the safer and more portable choice.
Frequently Asked Questions
What does Hex(255) return in VBA?
It returns the string FF. Hexadecimal 255 is two F digits because each F represents 15, and 15 × 16 + 15 equals 255.
Is Hex a built-in Excel formula?Hex is a VBA function, not a standard worksheet formula. In a cell, use DEC2HEX, or call a public VBA user-defined function from a macro-enabled workbook with macros enabled.
How do I add leading zeros to VBA Hex output?
Convert the value, then pad the resulting text to the required length. For example, the eight-character function above turns 255 into 000000FF. Choose the width for the format you actually need.
Does Hex work with negative numbers?
Yes, but negative values are represented according to signed numeric conventions and the type or width involved. For a predictable result, define the intended data type, bit width, and signedness rather than assuming every negative value should use the same number of hex digits.
Can I use VBA Hex in Excel for the web?
No. Excel for the web does not run VBA macros or VBA user-defined functions. Use a built-in worksheet function such as DEC2HEX for a cell-based conversion, or open the workbook in desktop Excel to run VBA.
Related
- How to Make Serial Numbers in Excel: 4 Easy Methods
- Color Certain Words in Excel: A Step-by-Step Guide
- How to Make Every Other Line a Color in Excel Quickly
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Outlook VBA: How to Pull and Export Mail DataTo pull mail data with VBA, use classic Outlook for Windows’ object model to select a folder, loop…
- Excel VBA Find Exact Match: Find Whole-Cell ValuesIn Excel VBA, set the LookAt argument of Range.Find to xlWhole to match an entire cell rather than…
- VBA Loop Through Worksheets: Examples and TipsTo loop through every worksheet in an Excel workbook, declare a Worksheet variable and use For Each ws…
- Excel VBA On Error MsgBox: A Practical GuideIn Excel VBA, use On Error GoTo HandlerName to send a runtime error to a handler, then show…
- Excel VBA Input Box Dropdown List: Options and SetupExcel’s built-in VBA InputBox does not support a dropdown list. To let someone choose from a visible list,…
- VBA Loop Array: Examples, Bounds, and Best PracticesA VBA array loop visits array elements one at a time, usually with a For loop using LBound…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.