As I understand, there are the 2 different ways to categorize data types in VBA.
I would assume that object types are the same as reference types. But I read that there is a difference regarding assignment between object and non-object types:
Dim i As Integer
i = 1
Dim chrt As Chart
Set chrt = something
Notice the "Set". Now in the following link, String is categorized as reference type.
http://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
But
Dim str As String
Set str = "abc"
is wrong and
Dim str As String
str = "abc"
is correct. Thus reference type and object type is not equivalent. What is the difference?
Your MSDN link is referring to Visual Studio 2013 (.NET), where String
is indeed an object (like everything in the .net framework).
VBA strings are values, not objects.
As I understand, there are the 2 different ways to categorize data types in VBA.
- Object type vs. Non-Object
- Value type vs. Reference type
It's simpler than that. An object type is a reference type, and a non-object type is a value type.
In VBA object references are assigned using the Set
keyword; in the past, values used to be assigned using the Let
keyword (I believe that still works, for compatibility reasons); that's why property setters use Let
for value types, as in Public Property Let Foo(value As Integer)
, and Set
for reference types, as in Public Property Set Foo(value As Object)
.
The language evolved and the Let
keyword was eventually dropped for value assignations; Set
remained required, for object reference assignations.
But in VBA a String
is a value, like an Integer
or a Boolean
.
VBA does have Value Types and Reference Types, but neither Strings
nor Arrays
fall neatly into either category.
It's informative to look at the definitions of Value types and Reference Types:
Value Type
- A data type is a value type if it holds the data within its own memory allocation.
Reference Type
- A reference type contains a pointer to another memory location that holds the data.
All Objects
use pointers, so they are all Reference Types
, while the following store their value at their memory location, so they are all Value Types
:
But Strings
and Arrays
are different. They do use pointers, so technically they are Reference Types
, but the VBA language semantically treats Strings
and Arrays
as Value Types
.
As such, when working with Strings
and Arrays
, VBA has the following behaviors:
It is not necessary to use the Set
keyword when assigning to a String
or Array
(unless you're assigning to a member of an Array
of objects).
Assigning the value of one String
or Array
to another creates a copy of the value.
The equality operator for comparing Strings
is the =
operator.
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