How to convert utf-32 code like U+20000 into character in VBA?

1.2k views Asked by At

If s contains 20000 and j is Len(s) the following

Dim b(1 To 8)
b() = ChrW("&H" & Mid$(s, 1, j - 4)) & ChrW("&H" & Mid$(s, j - 3))

does not work. It returns 2 characters while U+20000 is a single.

1

There are 1 answers

4
Dims On

Better code is based on here example: http://www.vbforums.com/archive/index.php/t-526476.html

Public Function ChrU(UCode As String) As String

Dim CharCode As Long
CharCode = Val("&H00" & Right(UCode, Len(UCode) - 2))

If CharCode < 0 Then
    CharCode = CharCode + 65536
End If

Dim lngChar As Long
If CharCode >= 0 Then
    If CharCode < &HD800& Then
        ChrU = ChrW$(CharCode)
        Exit Function
    ElseIf CharCode < &HDC00& Then
        ' UTF-16 surrogates are invalid in UTF-32
    ElseIf CharCode < &HFFFF& Then
        ChrU = ChrW$(CharCode)
        Exit Function
    ElseIf CharCode < &H10FFFF Then
        lngChar = CharCode - &H10000
        ChrU = ChrW$(&HD800& Or (lngChar \ 1024)) & ChrW$(&HDC00& Or (lngChar And &H3FF&))
        Exit Function
    End If
End If
Err.Raise 5
End Function