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 Expert (801 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 Expert (801 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
Ask any questions you have about VBA and Python and our community will help answer them. wellsr Q&A is the standalone question and answer platform for wellsr.com. If you have a question about one of our specific tutorials, please include a link back to the tutorial.

Getting Started
Register
VBA Cheat Sheets (On Sale Now)

Looking for something else? Hire our team directly through ourVBA Help page, instead.

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

...