ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Discussion (Misc queries) (https://www.excelbanter.com/excel-discussion-misc-queries/)
-   -   Using "Set" variable (https://www.excelbanter.com/excel-discussion-misc-queries/83078-using-set-variable.html)

Jeff

Using "Set" variable
 
I was looking over the "Set" variable in the help.

It gave the example:

Dim YourObject, MyObject, MyStr
Set MyObject = YourObject ' Assign object reference.
' MyObject and YourObject refer to the same object.
YourObject.Text = "Hello World" ' Initialize property.
MyStr = MyObject.Text ' Returns "Hello World".
' Discontinue association. MyObject no longer refers to YourObject.
Set MyObject = Nothing ' Release the object.

When should you use this? Does it have any advantage over just assigning
MyObject = "Hello World"

Thanks


Bob Phillips

Using "Set" variable
 
You have to use when referring to an object, e.g.

Set MyObject = Range("A1")

In the case MyObject will be a range variable that points to A1 and so you
can access any of the properties of that object via the range variable, such
as

MyObject.Font.Bold = True

If you are not referring to the object but a property of it that object, you
would not use Set, such as

MyValue = Range("A1").Value

In this case MyValue just contains the value in cell A1, and you do not have
access to an of the other properties of A1.

So, it is horses for courses.

--
HTH

Bob Phillips

(remove nothere from email address if mailing direct)

"Jeff" wrote in message
...
I was looking over the "Set" variable in the help.

It gave the example:

Dim YourObject, MyObject, MyStr
Set MyObject = YourObject ' Assign object reference.
' MyObject and YourObject refer to the same object.
YourObject.Text = "Hello World" ' Initialize property.
MyStr = MyObject.Text ' Returns "Hello World".
' Discontinue association. MyObject no longer refers to YourObject.
Set MyObject = Nothing ' Release the object.

When should you use this? Does it have any advantage over just assigning
MyObject = "Hello World"

Thanks





All times are GMT +1. The time now is 04:19 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com