首页 > 解决方案 > 在 VBA 中使用多种语言(英文、中文、日文)

问题描述

我需要能够在 VBA 中使用多种语言(英文、中文和日文)的字符串。仅当存在一种语言时,更改计算机的区域/区域设置才有效。有人可以帮忙吗?

示例代码

dim x as string
dim y as string
dim z as string
x = "English text"
y = "尊敬的"
z = "こんにちは"

标签: vbaexcelunicode

解决方案


ashleedawg 的建议有一个简单的替代方案:

使用字节数组而不是字符串来声明字符串。这样,VBA IDE 可以独立于区域设置存储数据。

我使用以下函数在 VBA 中声明字节数组(注意:如果您传递除字节以外的任何内容,则会出错):

Public Function ByteArray(ParamArray bytes() As Variant) As Byte()
    Dim output() As Byte
    ReDim output(LBound(bytes) To UBound(bytes))
    Dim l As Long
    For l = LBound(bytes) To UBound(bytes)
        output(l) = bytes(l)
    Next
    ByteArray = output
End Function

如果你有这个,你可以执行以下操作:

dim x as string
dim y as string
dim z as string
x = "English text" 
'Or: x = ByteArray(&H45,&H0,&H6E,&H0,&H67,&H0,&H6C,&H0,&H69,&H0,&H73,&H0,&H68,&H0,&H20,&H0,&H74,&H0,&H65,&H0,&H78,&H0,&H74,&H0)
y = ByteArray(&HA,&H5C,&H6C,&H65,&H84,&H76)
z = ByteArray(&H53,&H30,&H93,&H30,&H6B,&H30,&H61,&H30,&H6F,&H30)

要获取这些字节数组,我使用以下工作表函数:

Public Function UnicodeToByteArray(str As String) As String
    If Len(str) = 0 Then Exit Function
    Dim bytes() As Byte
    bytes = str
    Dim l As Long
    For l = 0 To UBound(bytes) - 1
        UnicodeToByteArray = UnicodeToByteArray & "&H" & Hex(bytes(l)) & ","
    Next
    UnicodeToByteArray = UnicodeToByteArray & "&H" & Hex(bytes(UBound(bytes)))
End Function

您可以在工作表中使用它(例如=UnicodeToByteArray(A1),其中 A1 包含字符串),然后将结果复制粘贴到 VBA。

您可以直接将字符串分配给字节数组并反转。

请注意,Unicode 支持在整个 VBA 中有所不同。例如MsgBox z,将产生问号,同时Cells(1,1).Value = z将 A1 设置为所需的字符串。


推荐阅读