如何在 VBA 中指定货币文字

1 ms-access vba

如果我想定义一个日期文字,我会编写以下内容:

将 myDate 调暗为日期 = #1/1/2021#

我应该使用什么字符来对货币变量执行类似的操作?那是

货币金额变暗 = ?200.00? 应该用什么字符“?” 使用VBA时?

Mat*_*don 5

在 VBA 中,声明不能与同一指令中的赋值合法地连接,因此:

Dim myDate As Date
myDate = #1/1/2021#
Run Code Online (Sandbox Code Playgroud)

为了讨论的目的,区分变量文字值很重要,因为变量的声明类型与文字的类型无关——这非常令人困惑,但也完全合法:

Dim myDate As Long
myDate = #1/1/2021#
Run Code Online (Sandbox Code Playgroud)

我们这里讨论的是文字。

如果数字文字Integer在 -32767 和 32767 之间,则它是文字;Long如果它在 -2147483647 和 2147483647 之间,则它是文字;否则Double(VBE 会自动添加#类型提示)。

这意味着200inmyAmount = 200是一个Integer文字,如果我们输入200.00VBE 会将其“美化” 200#(使其成为Double文字)。

用于Currency文字的类型提示字符是@,因此200inmyAmount = 200@CurrencyVBA 编译器理解的值。

但这并不重要,因为 VBA 将为我们做大量加宽(也缩小Integer)隐式类型转换:如果我们将文字分配给Currency变量,则该Integer值将转换为“适合”保留的Currency“桶”。因此,如果我们声明myAmount As Currency然后将其分配给文字值200Integer文字),如果我们询问 VBA 类型是什么myAmount,我们将得到声明的类型 - Currency

换句话说,将一个Integer或一个Double文字分配给Currency变量是完全合法的,这使得类型提示的文字在绝大多数情况下变得有些尴尬,实际上并不属于:

Dim myAmount As Currency

myAmount = 200 'integer literal
Debug.Print TypeName(myAmount) 'currency

myAmount = 200# 'double literal
Debug.Print TypeName(myAmount) 'currency

myAmount = 200@ 'currency literal
Debug.Print TypeName(myAmount) 'currency
Run Code Online (Sandbox Code Playgroud)

当我们放弃声明的类型并使用 aVariant代替(隐式或非隐式)时,事情会变得很有趣:

Dim myAmount 'As Variant

myAmount = 200 'integer literal
Debug.Print TypeName(myAmount) 'integer

myAmount = 200# 'double literal
Debug.Print TypeName(myAmount) 'double

myAmount = 200@ 'currency literal
Debug.Print TypeName(myAmount) 'currency
Run Code Online (Sandbox Code Playgroud)

日期文字#两侧都需要“分隔符”,因为/日期分隔符在 VBA(以及许多其他语言)中具有另一种语法含义:在其他上下文中,它是除法运算:从某种意义上说,#分隔符与"双引号用于分隔字符串文字,而不是用于@键入提示。

  • @ErikA 一个很好的观点,尽管 IMO “作为货币”在可读性方面得分比“5@”高得多……需要输入的几个额外字符是值得的;-) (2认同)