Skip to content

Instantly share code, notes, and snippets.

@yadimon
Last active February 11, 2023 08:05
Show Gist options
  • Save yadimon/ce1d04b88de17064bfae to your computer and use it in GitHub Desktop.
Save yadimon/ce1d04b88de17064bfae to your computer and use it in GitHub Desktop.
Function to unescape UTF-8 escaped content for VBA
'modified from http://needtec.sakura.ne.jp/codeviewer/index.php?id=2
Public Function UnescapeUTF8(ByVal StringToDecode As String) As String
Dim i As Long
Dim acode As Integer, sTmp As String
On Error Resume Next
If InStr(1, StringToDecode, "\") = 0 And InStr(1, StringToDecode, "%") = 0 Then
UnescapeUTF8 = StringToDecode
Exit Function
End If
For i = Len(StringToDecode) To 1 Step -1
acode = Asc(Mid$(StringToDecode, i, 1))
Select Case acode
Case 48 To 57, 65 To 90, 97 To 122
' don't touch alphanumeric chars
DoEvents
Case 92, 37: ' Decode \ or % value with uXXXX format
If Mid$(StringToDecode, i + 1, 1) = "u" Then
sTmp = CStr(CLng("&H" & Mid$(StringToDecode, i + 2, 4)))
If IsNumeric(sTmp) Then
StringToDecode = Left$(StringToDecode, i - 1) & ChrW$(CInt("&H" & Mid$(StringToDecode, i + 2, 4))) & Mid$(StringToDecode, i + 6)
End If
End If
Case 37: ' % not %uXXXX but %XX format
sTmp = CStr(CLng("&H" & Mid$(StringToDecode, i + 1, 2)))
If IsNumeric(sTmp) Then
StringToDecode = Left$(StringToDecode, i - 1) & ChrW$(CInt("&H" & Mid$(StringToDecode, i + 1, 2))) & Mid$(StringToDecode, i + 3)
End If
End Select
Next
UnescapeUTF8 = StringToDecode
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment