How do I display a messagebox with unicode characters in VBA?

二次信任 提交于 2019-12-30 18:45:08

问题


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

回答1:


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
    Prompt = Prompt & VbNullChar 'Add null terminators
    Title = Title & vbNullChar 
    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


来源:https://stackoverflow.com/questions/55210315/how-do-i-display-a-messagebox-with-unicode-characters-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!