Ad space (banner)
Lesson 13 / 20

Object variables and working with worksheets

This lesson covers holding a sheet in an object variable.

You declare it with Dim name As Worksheet and assign a particular sheet with Set name = Worksheets("SheetName"). Watch out for the Set — it is easy to leave out.

The sample code declares Dim ws As Worksheet, assigns a sheet with Set ws = Worksheets("Sheet1"), and then reaches cells as ws.Range("A1").

A common early stumble is forgetting Set when assigning an object. Unlike assigning a number or a string, putting an object into a variable always needs Set.

In professional work, holding sheets in object variables keeps macros that juggle several sheets much tidier.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run VBA directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)