Excel VBA格式化十六进制

时间:2016-09-05 02:00:19

标签: excel vba excel-vba hex

我想将3位长的十六进制转换为6位数。例如12F shd是00012F。我尝试了这段代码,但它没有用。

endadd = Format(endadd, "000000") 

2 个答案:

答案 0 :(得分:1)

正如Scott Craner指出的那样,一个简单的Right("000000" & endadd,6)可以很好地工作,但Right$("000000" & endadd,6)稍快一点。

此外,从性能角度来看,它实际上取决于endadd值的原始来源是字符串还是数字。

'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)

10米操作循环的结果:

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
======================================================

答案 1 :(得分:0)

您应该实现以下功能

    Public Function HexByte2Char(ByVal Value As Byte) As String
      ' Return a byte value as a two-digit hex string.
      HexByte2Char = IIf(Value < &H10, "0", "") & Hex$(Value)
    End Function

Usage
Dim s As String
s = HexByte2Char(dec_number)