I have a string containing unicode characters in VBA.
I want to display that string in a message box containing it.
However, instead of the string, the message box only contains a questionmark.
MCVE:
Dim s As String
s = ChrW(5123)
MsgBox s
MsgBox is not compatible with non-ANSI unicode characters.
We can display message boxes with the WinAPI MessageBoxW function, however, and that is .
Let's declare that function, and then create a wrapper for it that's nearly identical to the VBA MsgBox function:
Private Declare PtrSafe Function MessageBoxW Lib "User32" (ByVal hWnd As LongPtr, ByVal lpText As LongPtr, ByVal lpCaption As LongPtr, ByVal uType As Long) As Long
Public Function MsgBoxW(Prompt As String, Optional Buttons As VbMsgBoxStyle = vbOKOnly, Optional Title As String = "Microsoft Access") As VbMsgBoxResult
MsgBoxW = MessageBoxW(Application.hWndAccessApp, StrPtr(Prompt), StrPtr(Title), Buttons)
End Function
This function is only compatible with Microsoft Access. However, for Excel you can swap Application.hWndAccessApp with Application.hWnd to make it work. For other VBA compatible applications, you'll have to find the appropriate way to get the hWnd.
You can use it like MsgBox, as long as you don't use the context-dependent help functionality:
Dim s As String
s = ChrW(5123)
MsgBoxW s
vbNullChar is not necessary. I use Application.ActiveWindow.hWnd in Word and Excel instead of Application.hWndAccessApp.BSTR. It consists of a 4 byte unsigned integer that stores the length of the string in bytes followed by the string data itself as wide characters (2 bytes per character) and terminated with 2 null bytes. So, BSTR strings are length prefixed and null-terminated. The internal pointer retrieved by the StrPtr() function points to the memory location of the string data, not the length prefix. This means that a VBA String vbastr can be passed via StrPtr(vbastr) directly to API functions that require a pointer to a null-terminated C-String.BSTR contained a null terminator in addition to specifying the length up front, always thought that strings with specified length didn't contain it. I've edited the answer.An alternative could be my ModernBox:
MsgMox ChrW(5125) & ChrW(5123) & ChrW(5121) & ChrW(5130), vbInformation, "Unicode"
Display:
appname-vbatags; Excel was to be the first.access-vbabut missing thevbatag, the one combination I'd have to clean up for the next step (mergingaccess-vbaintoms-access) to even work.-vbatags has been a huge issue for too long however, which is why I'm driving this manually now. While access-vba gets a stay of execution, that's only until the CMs regain the ability to do tag burninations properly again (Shog and Jon, both gone, were the only ones who knew how and had the access for it).