Convert ASCII to UTF-8 using VBA

No Comments
Uncategorized

Recently, I had the need for a function to properly encode ASCII characters into their UTF-8 equivalent using VBA (Visual Basic for Applications), specifically an Excel document which was making API calls to the Google Maps API. However, to my dismay, no functions existed for this task, and the built in character stream classes converted the characters into a format ignored by the Google API. So, I had to look up the UTF-8 table, along with each characters Hexadecimal equivalent (for both ASCII and UTF-8), and was able to come up with this function.

Now, keep in mind that this does not handle every character known to man. For my use, I had to encode European accented characters used in the German and French languages. For anything else you’ll probably need to make this function more robust.

Public Function tlhAsciiToUtf8(ByRef strText As String) As String
 Dim hexString As Long
 Dim newval As Long
 hexString = Val("&h" & strText)
 If hexString <= 127 Then
   tlhAsciiToUtf8 = "%" & strText
 ElseIf hexString <= 191 Then
   tlhAsciiToUtf8 = "%C2%" & strText
 ElseIf hexString <= 255 Then
   newval = 49856 + hexString
   tlhAsciiToUtf8 = "%" & Mid(Hex(newval), 1, 2) & "%" & Mid(Hex(newval), 3, 2)
 Else
   MsgBox ("NON ASCII CHARACTER: " & hexString)
 End If
End Function
  • Digg
  • Google Bookmarks
  • MySpace
  • Reddit
  • Facebook
  • NewsVine
  • StumbleUpon
  • Twitter
  • WordPress
  • Delicious
  • Yahoo Messenger
  • AIM
  • Bebo
  • Share/Bookmark

Related posts:

  1. Amazon PHP Authentication Function Amazon recently changed their requirements for sending information back and...
  2. Chinese Characters not displaying in Internet Explorer 8 How to get foreign characters, including Japanese, Chinese, and other...

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>