如何在 VBA 中显示带有 unicode 字符的消息框?

问题描述:

我在 VBA 中有一个包含 unicode 字符的字符串.

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 与非 ANSI unicode 字符不兼容.

MsgBox is not compatible with non-ANSI unicode characters.

我们可以使用 WinAPI MessageBoxW 函数显示消息框,但是,就是 .

We can display message boxes with the WinAPI MessageBoxW function, however, and that is .

让我们声明这个函数,然后为它创建一个几乎与 VBA MsgBox 函数相同的包装器:

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

此功能仅与 Microsoft Access 兼容.但是,对于 Excel,您可以将 Application.hWndAccessAppApplication.hWnd 交换以使其工作.对于其他 VBA 兼容的应用程序,您必须找到合适的方法来获取 hWnd.

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.

你可以像 MsgBox 一样使用它,只要你不使用上下文相关的帮助功能:

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