Using Object Variables

If you find that you're using the same object reference many times, you can set a variable for the object and subsequently use the variable in place of the object reference. This way, you'll only need to call the object accessor once, when you set the variable, instead of calling it each time you want to refer to the object. The following example calls the Workbooks method and the Sheets method twice each.


Workbooks(1).Sheets(1).Range("c5").Value = 10
Workbooks(1).Sheets(1).Range("d10").Value = 12

You can optimize this example by setting an object variable. The following example calls the Workbooks method and the Sheets method only once each.


Set sheet = Workbooks(1).Sheets(1)
sheet.Range("c5").Value = 10
sheet.Range("d10").Value = 12