Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA formatting Hexadecimal

Tags:

excel

hex

vba

I want to convert hexadecimal which are 3 digits long into 6 digits. For example 12F shd be 00012F. I tried this code but it didnt work.

endadd = Format(endadd, "000000") 
like image 245
Manick9 Avatar asked Nov 08 '22 09:11

Manick9


1 Answers

As Scott Craner pointed out, a simple Right("000000" & endadd,6) will work perfectly well, but Right$("000000" & endadd,6) is slightly faster.

Furthermore, from a performance perspective, it really depends on whether the original source of the endadd value is a String or Numeric.

'CONCAT String Approach
'If the hex source is a string, then this is the most efficient approach
formattedHex = Right$("000000" & "12F", 2)

'CONCAT Numeric Approach
'But if the hex source is a numeric, then this hex conversion AND concatenation is required, but it is SLOW
formattedHex = Right$("000000" & Hex$(&H12F), 2)

'ADDITION/OR Numeric Approach
'When the hex source is numeric it is more efficient to use a bit trick to add AND convert
formattedHex = Right$(Hex$(&H1000000 + &H12F), 2)
formattedHex = Right$(Hex$(&H1000000 Or &H12F), 2)

Results from a 10m operation loop:

Approach                  | Using Right | Using Right$ |
==========================+=============================
CONCAT String Approach    | 1.59s       | 1.40s
CONCAT Numeric Approach   | 2.63s       | 2.33s
ADDITION Numeric Approach | 1.74s       | 1.60s
======================================================
like image 133
ThunderFrame Avatar answered Nov 15 '22 06:11

ThunderFrame