9

我想(在 VBA 类模块中)声明一些包含日文字符的私有常量字符串。有没有办法构造String可以在声明中被接受为初始化器的文字(或以某种方式组合文字)Const?即类似的东西:

Private Const MY_CONST = ...

或者

Private Const MY_CONST As String = ...

我使用 MS Excel v14.0.6112.5000(MS Office Professional Plus 2010)。

什么不起作用

  • 将日文字符直接粘贴到字符串文字中(例如... = "変数"),因为 VBA 编辑器会弄乱字符;
  • 使用ChrW()ChrW$()(例如),因为在初始化程序... = ChrW$(22793) & ChrW$(25968)中不允许函数调用。Const

不喜欢的

  • Const通过创建返回字符串来伪造Private Property Get,因为每次我访问该属性时都会重新创建字符串(另外,令人困惑和丑陋......但是,好吧,最后两件事是一个口味问题)。
4

3 回答 3

4

通过创建 Private Property Get 返回字符串来伪造 Const,因为每次我访问该属性时都会重新创建字符串(另外,这令人困惑且丑陋……但是,好吧,最后两件事只是个人喜好问题)。

您无需在每次访问该属性时重新创建字符串。

虽然这仍然很难看,但创建一个只读属性(本质上Const,因为它没有过程),并在事件Property Let中构造字符串:Class_Initialize

'## CLASS MODULE
Private pUnicodeString As String

Sub Class_Initialize()
    pUnicodeString = ChrW(22793) & ChrW(25968)
End Sub

Property Get UnicodeString() As String
    UnicodeString = pUnicodeString
End Property

然后像这样调用它:

'## STANDARD MODULE
Sub Test()
Dim c As myClass
Set c = New myClass

[A1].Value = c.UnicodeString

End Sub
于 2014-05-15T14:17:10.017 回答
3

VBA源文件编码为Windows-1252,不支持日语。

您无法更改源文件的编码,因此您必须编写其二进制等效项,然后在使用之前对其进行转换

Const str = vbTab & "Ype" ' I use vbTab because the VBA editor replaces tabulation with spaces
'...
ustr = StrConv(str, vbFromUnicode)
'ustr value is now "変数"

使用记事本转换字符串:复制粘贴 unicode 字符串,将文件保存为 unicode(不是 utf-8)并以 ANSI 格式打开,然后将其复制粘贴到不带前两个字符(ÿþ)的 VBA 编辑器中,即是 BOM 标记

解释

変数是U+5909 U+6570unicode,是0x09 0x59 0x70 0x65UTF-16LE(Windows unicode encoding),这个序列对应<tab>YpeWindows-1252

于 2014-05-15T12:41:50.737 回答
2

另一种方法是将枚举与函数结合使用,以提供基于友好名称的 VBA 自动完成功能。我更喜欢这种方法,因为它将所有 Unicode 定义保存在一个地方,并在我的项目的其余部分使用可读的名称。

' List friendly names of Unicode characters
Public Enum eUnicodeConst
    RightArrow
    LeftArrow
    Clock2
End Enum

'---------------------------------------------------------------------------------------
' Procedure : UniConst
' Author    : Adam Waller
' Date      : 7/7/2020
' Purpose   : Search for characters: https://emojipedia.org/
'           : Look up UTF-16 Decimal value(s) from the following site:
'           : http://www.fileformat.info/info/unicode/char/search.htm
'---------------------------------------------------------------------------------------
'
Public Function UniConst(Text As eUnicodeConst) As String
    Select Case Text
        Case LeftArrow:     UniConst = ChrW(8592)
        Case RightArrow:    UniConst = ChrW(8594)
        Case Clock2:        UniConst = ChrW(55357) & ChrW(56657)
    End Select
End Function

现在在我的代码中,我可以在UniConst需要 Unicode 字符或片段的任何时候使用该函数,而无需查看字符代码。

在此处输入图像描述

于 2020-07-07T21:41:39.837 回答