tags:

views:

5889

answers:

6

Hopefully an easy question, but I'd quite like a technical answer to this!

What's the difference between:

i = 4

and

set i = 4

in VBA? I know that the latter will throw an error, but I don't fully understand why.

Many thanks!

+1  A: 

Set is used for setting object references, as opposed to assigning a value.

Jason Lepack
+8  A: 

In your case, it will produce an error. :-)

Set assigns an object reference. For all other assignments the (implicit, optional, and little-used) Let statement is correct:

Set object = New SomeObject
Set object = FunctionReturningAnObjectRef(SomeArgument)

Let i = 0
Let i = FunctionReturningAValue(SomeArgument)

' or, more commonly '

i = 0
i = FunctionReturningAValue(SomeArgument)
Tomalak
+6  A: 

From MSDN:

Set Keyword: In VBA, the Set keyword is necessary to distinguish between assignment of an object and assignment of the default property of the object. Since default properties are not supported in Visual Basic .NET, the Set keyword is not needed and is no longer supported.

Galwegian
Well found, but a link to the article you found on MSDN would be even better :)
Neil Barnwell
@Neil - the link is there if you click MSDN in my post.
Galwegian
When copying off the MSDN, then at least the correct article. This one is referring to VB.NET, not to VBA.
Tomalak
+1  A: 

Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it's doing an AddRef() call on the object to manage it's lifetime.

Sean
It's not only used for COM objects, but for all objects. The main reason you use SET is explained by Galwegian.
Ikke
+3  A: 

set is used to assign a reference to an object. The C equivalent would be

 int i;
int* ref_i;

i = 4; // Assigning a value (in VBA: i = 4)
ref_i = &i; //assigning a reference (in VBA: set ref_i = i
Treb
Tomalak
No quite the same, no. But close enough for me to understand the concept.
Treb
@Tomalak: You could use VarPtr()
Atmocreations
A: 

set is used to set references for already defined objects

ashok