代码之家  ›  专栏  ›  技术社区  ›  Nikhil Joseph

在VBA中使用多种语言(英语、中文、日语)

  •  0
  • Nikhil Joseph  · 技术社区  · 8 年前

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

    示例代码

    dim x as string
    dim y as string
    dim z as string
    x = "English text"
    y = "尊敬的"
    z = "こんにちは"
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Erik A    8 年前

    除了Ashleedawg的建议,还有一个简单的选择:

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

    我使用以下函数在VBA中声明bytearray(注意:如果传递的不是byte,则会出现错误):

    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)
    

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

    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。

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

    注意,整个VBA中对Unicode的支持各不相同。例如。 MsgBox z 会导致问号,而 Cells(1,1).Value = z 将A1设置为所需的字符串。