0 votes
in VBA by Beginner (6 points)
Let say I have a class module name A.

In A I define a member variable of type Scripting.Dictionary.

For example:
Public currentRowList As Scripting.Dictionary

and in Class_Initialize():
Set currentRowList = CreateObject("Scripting.Dictionary")

Then I create an object of of class A.
Dim a1 as A: set a1 = new A

Now I want to do as follows:
a1.currentRowList("key") = 1

From some reason I get the following error:
Wrong number of arguments or invalid property assignment.

The question is why I'm getting this error and how can I set the dictionary field.

1 Answer

+2 votes
by Skilled (520 points)
selected by
 
Best answer

I prefer early binding for Dictionary. In VBA Editor, pick Tools > References > Microsoft Scripting Runtime. 

Make your Class A like this:

Public currentRowList As Scripting.Dictionary
Private Sub Class_Initialize()
Set currentRowList = New Scripting.Dictionary
End Sub

Now put this in a standard module:

Sub test()
Dim a1 As A: Set a1 = New A
'use the Add method
a1.currentRowList.Add "key", 1
'or use a1.currentRowList.Item("key") = 1
'but not a1.currentRowList("key") = 1
Debug.Print a1.currentRowList.Keys(0), _
    a1.currentRowList.Items(0), _
    a1.currentRowList.Item("key")
End Sub

The tutorial Excel VBA Dictionary Keys and Items uses statements like 
dict("Alice") = "555-778-0131"
which are OK if Item is the default property of dict. But this does not work when your Dictionary is defined in a class module. The tutorial would be more correct if such statements were changed to 
dict.Item("Alice") = "555-778-0131"

 

by Beginner (6 points)
Thanks for your answer, but still I can't use it since I also need to change an existing value for a pecific key. How do I do that?
by Skilled (520 points)

Did you try this?
a1.currentRowList.Item("key") = 1

by Beginner (6 points)
+1
Yes. It works this way just fine:-)

Many thanks man!

Welcome to wellsr Q&A
wellsr Q&A is the VBA and Python programming community that rewards you for learning how to code.

Getting Started
Register
VBA Cheat Sheets (On Sale Now)

Earn free prizes for asking VBA and Python questions and for answering questions asked by others in our community.

Looking for something else? Hire our professional VBA Help, instead.

What makes us different?
Our points system rewards you with a chance for free gifts based on the quality of your questions and answers. All you have to do is post and you could get rewarded, like these members:

ParserMonster $25 Amazon Gift Card
Hightree $10 Amazon Gift Card
Thales1 $10 Amazon Gift Card
runfunke $10 Amazon Gift Card
coolag $10 Amazon Gift Card
Siew Hun $10 Amazon Gift Card

So, why don't you join us? It really is an encouraging way to motivate members in our VBA and Python community.

Register

For more programming tips visit the VBA Tutorials Blog and the Python Tutorials Blog.

...