I'm a beginner learning VBA currently, and confused by the inner workings of Set
. This started with me having great confusion as to why Set
was not needed for certain assignments. For example, the following block of code runs fine:
Block 1 Code:
TempPercentile = Application.WorksheetFunction.PercentRank(Range("L2", Range("L2").End(xlDown)), ActiveCell.Value)
However, this code throws a compile error with VBA complaining an object is needed:
Block 2 Code:
Set TempPercentile = Application.WorksheetFunction.PercentRank(Range("L2", Range("L2").End(xlDown)), ActiveCell.Value)
This occurs even when I declare TempPercentile
earlier in my code: Dim TempPercentile As Double
. My debugger highlights PercentRank
as the source of the error, but I actually believe it is because I am attempting to use Set
to create a new double
.
I understand from this StackOverflow post that Dim
is used to declare variables and objects, and Set
is used to set the value of an object-reference. Is the reason why the second block of code doesn't work because Set
is only used to set the value of objects, and TempPercentile
is a Double
? The mentioned SO post states that there is no use for Set
unless as an object reference. Is this because Set
calls some sort of Factory
constructor method (which obviously is not needed for a primitive)?
Second, is Set
simply creating a memory reference to the object, or is it actually duplicating the copy in memory?
Does Set
therefore function like a constructor in Java?
This article states that
the Set keyword is used to create new objects, creating a new Range, for example.
If this is true, doesn't this create lots of issues with performance? Every time you want to declare and set an object, you have to create a new object. I'm asking because if I have very large Objects
, like entire worksheets that I am trying to use Set
on, I do not want to overload memory.