Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

excel - Using multiple language (english, chinese, japanese) in VBA

I need to be able to use strings of multiple languages (english, chinese and japanese) in VBA. Changing the region/locale setting of the computer only works if there is one language. Could someone help?

Example code

dim x as string
dim y as string
dim z as string
x = "English text"
y = "尊敬的"
z = "こんにちは"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's a simple alternative to ashleedawg's suggestion:

Use bytearrays instead of strings to declare the strings. That way, the VBA IDE can store the data independent of locale settings.

I use the following function to declare bytearrays in VBA (Note: errors if you pass anything else than a 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

If you have this, you can do the following:

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)

To get these bytearrays, I use the following worksheet function:

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

You can use this in a worksheet (e.g. =UnicodeToByteArray(A1) where A1 contains the string), and then copy-paste the result to VBA.

You can directly assign strings to bytearrays and reversed.

Note that unicode support varies throughout VBA. E.g. MsgBox z will result in questionmarks, while Cells(1,1).Value = z will set A1 to the desired string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...