When I initiate a dictionary object in Excel VBA, I found out two methods:
CreateObject("Scripting.Dictionary")
(no "Microsoft Scripting Runtime");Dim dict As New Scripting.Dictionary
Both of them work on my machine. I am wondering is there any difference between these two methods?
Basic setup of a VBA Dictionary For early binding, start by opening the Visual Basic Editor by pressing Alt+F11 and going to Tools > References. Set a reference to the Microsoft Scripting Runtime object library.
The . exists() function checks if a key exists.
You can assign a Key to an Item when you add the Item to the Collection, but you cannot retrieve the Key associated with an Item nor can you determine (directly) whether a key exists in a Collection. Dictionaries are much friendly and open with their keys. Dictionaries are also considerably faster than Collections.
The only difference I know is the first one uses Late bind
and the second one uses Early bind
. The difference between the two is explained here.
Early bind has advantages. One of which is you can use Intellisense
to guide you on the available properties of the bound object that you can use in coding. Also, it is said that it is faster in terms of performance. You can also use built-in constant as is. No need to check it's equivalent value. This is discussed here.
Late bind has advantages as well specially if you bound objects that have different versions. This reduces the risk of runtime errors due to version incompatibility (also mentioned in the 1st link).
As for me, I always use Early bind during development so I can utilize Intellisense
. If there is a need to convert to Late bind, I'll do it later after I or the customer have done robust testing.
Additional:
When you use Early bind Don't Use Auto-Instancing Object Variables
as discussed by CPearson in his post here. Below is the excerpt from his blog.
For object type variables, it is possible to include the New keyword in the Dim statement. Doing so create what is called an auto-instancing variable. Again, while this may seem convenient, it should be avoided. Contrary to what some programmers may believe, the object isn't created when the variable declaration is processed. Instead, the object is created when it is first encountered in the code. This means that, first, you have limited control when an object is created. Second, it means that you cannot test whether an object is Nothing, a common test within code and a common testing and diagnostic technique.
So a better way to set your variable is:
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With