Why aren't parentheses required for add method of dictionary class?

拜拜、爱过 提交于 2019-12-23 01:38:09

问题


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.

So if D is an object of type dictionary, then vba expects: D.Add "key1", "value1"

and not:

D.Add("key1", "value1") <= this generates an error!

Contrasting the Add method with Exists:

Dictionary.Exists (Key as String)

The parentheses are actually expected:

V1 = D.Exists("key1")

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?


回答1:


In VBA, if you call a Sub with parameters, you can call it either with:

YourSub Parameter1

or

Call YourSub(Parameter1)

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)

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)...



来源:https://stackoverflow.com/questions/19126312/why-arent-parentheses-required-for-add-method-of-dictionary-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!