You are here KNOWLEDGE Excel Tips Excel Macros and VBA MsgBox with unicode string in VBA

Query, Share and Manage Excel workbooks on LAN, Internet

MsgBox with unicode string in VBA

Progamming VBA MsgBox in VBA can not display unicode string because it is ansi string (string 1 byte). How to display unicode string in MsgBox? I show you way using API function MessageBoxW to display unicode string.

In VBE/VBA, create a module, copy code bellow:

'****************************************
'Author: Nguyen Duy Tuan
'Tel : 0904.210.337
'E.Mail : tuanktcdcn@yahoo.com 
'Website: http://atoolspro.com - http://bluesofts.net
'****************************************
'Declaration API functions of User32.DLL. for Office 32 or 64-bit
#If VBA7 Then
Private Declare PtrSafe Function GetActiveWindow Lib "user32" () As LongPtr
Private Declare PtrSafe Function MessageBoxW Lib "user32" (ByVal hwnd As LongPtr, ByVal lpText As String, ByVal lpCaption As String, ByVal wType As Long) As Long
#Else
Private Declare Function GetActiveWindow Lib "user32" () As Long
Private Declare Function MessageBoxW Lib "user32" (ByVal hwnd As Long, ByVal lpText As String, ByVal lpCaption As String, ByVal wType As Long) As Long
#End If

Function MsgBoxUni(ByVal PromptUni As Variant, Optional ByVal Buttons As VbMsgBoxStyle = vbOKOnly, Optional ByVal TitleUni As Variant = vbNullString) As VbMsgBoxResult 
   'Function MsgBoxUni(ByVal PromptUni As Variant, Optional ByVal Buttons As VbMsgBoxStyle = vbOKOnly, Optional ByVal TitleUni As Variant, Optional HelpFile, Optional Context) As VbMsgBoxResult
   'BStrMsg,BStrTitle : La chuoi Unicode
   Dim BStrMsg, BStrTitle 
   'Hàm StrConv Chuyen chuoi ve ma Unicode
   BStrMsg = StrConv(PromptUni, vbUnicode) 
   BStrTitle = StrConv(TitleUni, vbUnicode) 
   MsgBoxUni = MessageBoxW(GetActiveWindow, BStrMsg, BStrTitle, Buttons) 
End Function 

Now you can run function MsgBoxUni() as MsgBox in VBA nut it display unicode string

Sub TestMsgBoxUni() 
   'Test trong Excel
   MsgBoxUni Range("B3").Value, vbInformation, Range("B4").Value 
End Sub 

On Excel sheet, cell B3 have prompt, B4 have title, all are unicode string

Download source:

http://www.bluesofts.net/Baiviet/Laptrinh/VB_VBA/MsgBoxUnicode.zip

Author: Nguyen Duy Tuan - http://bluesofts.net - http://atoolspro.com