为什么字典类的添加方法不需要括号? [英] Why aren't parentheses required for add method of dictionary class?
问题描述
字典类的add方法的VBA语法为:
The VBA syntax for the add method of the dictionary class is given as:
Dictionary.Add (Key as String, Item as Variant)
但是实际上包含这些括号会产生语法错误.
But actually including these parentheses generates a syntax error.
因此,如果D是字典类型的对象,则vba期望: D.添加"key1","value1"
So if D is an object of type dictionary, then vba expects: D.Add "key1", "value1"
而不是:
D.Add("key1","value1")< =会产生错误!
D.Add("key1", "value1") <= this generates an error!
将Add方法与现有方法进行对比:
Contrasting the Add method with Exists:
Dictionary.Exists (Key as String)
实际上应该加上括号:
V1 = D.Exists("key1")
V1 = D.Exists("key1")
那为什么为什么Add语法指定()却不实际期望它们(如果使用它们,甚至会产生错误),而Exists语法却指定了它们却确实期望它们? >
So why is it that the Add syntax specifies ()'s, but doesn't actually expect them (and even generates an error if they are used), while the Exists syntax specifies them and does actually expect them?
推荐答案
在VBA中,如果您调用带参数的Sub,则可以使用以下方法之一进行调用:
In VBA, if you call a Sub with parameters, you can call it either with:
YourSub Parameter1
或
Call YourSub(Parameter1)
请注意,YourSub (Parameter1)
实际上会将Parameter1转换为字符串,然后将其移交给YourSub-这当然不是您想要的!!
Note that YourSub (Parameter1)
will actually cast Parameter1 to a string and then hand it over to YourSub - which is most certainly not what you want!!!
如果它是一个函数,则可以将其命名为:
In case it is a Function, you would call it:
result = YourFunction(Parameter1)
对于Dictionary对象,.Add
是方法/子,即您使用dict.Add Key, Value
,而.Exists
是函数,因此您需要使用if dict.Exist(Key)...
In case of a Dictionary object, .Add
is a method/sub, i.e. you use dict.Add Key, Value
, while .Exists
is a function, so you need to use if dict.Exist(Key)...
这篇关于为什么字典类的添加方法不需要括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!