I know this is an old post, but it's highlighted on Google, so I'd like to point out that Vladimir's version has an oversight: Format() can only format numbers in decimal format. So Hex2Uni will return incorrect results for bytes from A-F, as Format will see them as text instead of numbers and not pad them. Unicode 0A0A will come full circle as AA (=00AA), for example. Also, the use of Trim() in Uni2Hex prevents the function from returning the Unicode value for space.
Here are versions that will similarly handle surrogate pairs; in fact, I just have them convert the entire string to a hex sequence and vice-versa:
Code:
Function Uni2Hex(Txt As String) As String
Dim n As Long
For n = 1 To Len(Txt)
Uni2Hex = Uni2Hex & Right("000" & Hex(AscW(Mid(Txt, n, 1))), 4)
Next n
End Function
Function Hex2Uni(ByVal Txt As String) As String
Dim n As Long, l As Long
Txt = Replace(Replace(Replace(LCase(Txt), "0x", ""), "&h", ""), " ", "") 'optional clean-up
l = WorksheetFunction.Ceiling(Len(Txt), 4)
If l > 0 Then
Txt = Right("000" & Txt, l)
For n = 1 To l Step 4
Hex2Uni = Hex2Uni & ChrW(CInt("&h" & Mid(Txt, n, 4)))
Next n
End If
End Function
Like this thread? Share it with others