tags:

views:

36

answers:

3

Pardon me as am a newbie in VBA, VB.NET.

Sometimes I use

Dim r as Range
r = Range("A1")

Other times I use

Set r = Range("A1")

What is the difference? And when should I use what? Can someone please point me to a tutorial on the difference?

+1  A: 

Dim: you are defining a variable (here: r is a variable of type Range)

Set: you are setting the property (here: set the value of r to Range("A1") - this is not a type, but a value).

You have to use set with objects, if r were a simple type (e.g. int, string), then you would just write:

Dim r As Integer r=5

Tobias Schittkowski
A: 

Dim simply declares the value and the type.

Set assigns a value to the variable.

Justin Niessner
+1  A: 

There's no reason to use set unless referring to an object reference. It's good practice to only use it in that context. For all other simple data types, just use an assignment operator. It's a good idea to dim (dimension) ALL variables however:

Examples of simple data types would be integer, long, boolean, string. These are just data types and do not have their own methods and properties.

Dim i as Integer
i = 5

Dim myWord as String
myWord = "Whatever I want"

An example of an object would be a Range, a Worksheet, or a Workbook. These have their own methods and properties.

Dim myRange as Range
Set myRange = Sheet1.Range("A1")

If you try to use the last line without "Set", VB will throw an error. Now that you have an object declared you can access its properties and methods.

myString = myRange.Value
Michael
Can I please know which tutorial or book did you refer to understand this?
Ram