Dim ws As Worksheet declares a variable named ws that can refer to an Excel worksheet, but it does not select or assign a worksheet by itself. To use it, assign a worksheet object with Set, such as Set ws = ThisWorkbook.Worksheets("Data").
What the declaration means
The statement has three parts. Dim declares a variable, ws is the variable’s name, and As Worksheet specifies its data type. In VBA, a worksheet is an object: it represents one worksheet tab and provides properties and methods for working with that sheet.
The name ws is a common abbreviation for “worksheet,” not a special VBA keyword. You could use another valid name, such as targetSheet, if that makes the code easier to read. VBA is not case-sensitive, so Dim ws As Worksheet and Dim WS As Worksheet mean the same thing. Consistent capitalization can still help make code more readable.
Declaring a variable gives VBA a place to hold a reference to an object. It does not create a new worksheet, activate a tab, or automatically point to the sheet currently visible in Excel. Those are separate actions, and often you do not need to activate a sheet at all.
How to assign a worksheet to ws
Because a worksheet is an object, use the Set statement to assign it. The following procedure refers to a worksheet named Data in the workbook that contains the VBA code:
Sub ReadDataSheet()
Dim ws As Worksheet
' Refer to the Data worksheet in this workbook.
Set ws = ThisWorkbook.Worksheets("Data")
MsgBox ws.Name
End Sub
ws.Name reads the worksheet’s name, so this example displays Data if that worksheet exists in the referenced workbook. The key distinction is between assigning an object and assigning an ordinary value: object variables use Set, while a value assignment such as ws.Name = "Archive" does not use it.
You can also assign a worksheet by its position in the collection, for example ThisWorkbook.Worksheets(1). That means the first worksheet in the workbook’s Worksheets collection, not necessarily a sheet with a fixed name. If sheets are reordered, the first sheet may change, so a name is usually clearer when the code depends on a particular tab.
Using ws to work with cells and ranges
Once ws refers to a worksheet, qualify sheet-specific references with it. This makes it clear which sheet a cell or range belongs to, regardless of which worksheet is active. For example, this procedure writes a value to cell A1 on the Data sheet:
Sub WriteStatus()
Dim ws As Worksheet
' Refer to the sheet, then qualify the cell reference.
Set ws = ThisWorkbook.Worksheets("Data")
ws.Range("A1").Value = "Ready"
End Sub
Here, Range("A1") belongs to ws, and Value is the cell property being changed. The same pattern works for other worksheet members, such as ws.Cells(2, 3).Value for row 2, column 3, or ws.Rows(1).Hidden to inspect or change whether the first row is hidden.
Unqualified references can behave differently than intended. For example, Range("A1") on its own refers to the active sheet in the relevant context. If a user clicks another tab before running a macro, an unqualified reference may read or change the wrong sheet. Writing ws.Range("A1") removes that ambiguity.
Choose the right workbook reference
A worksheet belongs to a workbook, so choosing the right workbook is as important as choosing the right sheet. ThisWorkbook means the workbook that contains the running VBA code. ActiveWorkbook means the workbook that is currently active in Excel. They may be different—for example, when a macro stored in a separate macro workbook operates on the workbook currently open in front.
Use ThisWorkbook when the macro should always target the file where its code is stored. Use ActiveWorkbook only when the user’s currently active workbook is intentionally the target. If you already have a workbook variable, you can qualify the reference through it, as in wb.Worksheets("Data"); that approach is useful when the macro opens or processes a specific workbook.
Fully qualifying the reference also makes code easier to review. A line such as ThisWorkbook.Worksheets("Data").Range("A1").Value identifies the workbook, sheet, and cell in one expression. Storing the worksheet in ws is often more convenient when several lines will work with the same sheet.
Looping through worksheets
A worksheet variable can represent each sheet in a collection as a loop runs. This example displays every worksheet name in the workbook containing the code:
Sub ListWorksheetNames()
Dim ws As Worksheet
' Visit each worksheet, excluding chart sheets.
For Each ws In ThisWorkbook.Worksheets
Debug.Print ws.Name
Next ws
End Sub
Debug.Print sends the names to the Immediate window in the Visual Basic Editor; it does not write them into worksheet cells. The loop variable ws refers to a different worksheet on each pass. A For Each loop is generally easier to maintain than a loop that assumes a particular number of sheets.
The collection name matters. Worksheets contains worksheet tabs, while Sheets can include both worksheets and chart sheets. A variable declared As Worksheet is appropriate when the code needs worksheet features such as cells and ranges. If a loop through Sheets can encounter chart sheets, declaring the loop variable as Worksheet may not suit every item.
Why declare it As Worksheet?
VBA has several related Excel object types. A Workbook represents a file, a Worksheet represents a worksheet tab, and a Range represents one or more cells. Using the specific type that matches the object makes the code’s purpose clearer and enables VBA’s editor to offer relevant properties and methods while you write.
For a single cell or cell block, declare a separate variable as Range if you want to store that range. For an entire workbook, use Workbook. Choosing Object instead of Worksheet is possible, but it is a less specific declaration: VBA cannot check as many member references at compile time, and the code is less self-explanatory. Use the more specific type when you know what kind of object the variable should hold.
A worksheet variable is not the same as a worksheet’s tab name. The name is a property of the object, accessed through ws.Name. The variable is simply your code’s reference to that object. If a tab is renamed, a reference already assigned to its worksheet object can still refer to that worksheet during the procedure, although code that looks it up later by the old name will need updating.
Scope, Option Explicit, and object lifetime
In a procedure, a declaration such as Dim ws As Worksheet makes ws a local variable, available within that procedure. When the procedure ends, that local variable goes out of scope. If more than one procedure needs its own worksheet reference, each procedure can declare its own local variable; this generally makes dependencies easier to see.
Adding Option Explicit at the top of a VBA module requires variables to be declared before use. It can catch spelling mistakes such as writing wss on one line when the declared variable is ws. In the Visual Basic Editor, the setting to require declarations for new modules is under Tools > Options on Windows. It affects newly created modules; it does not automatically insert the statement into every existing module.
After assigning a worksheet, you can release the object reference with Set ws = Nothing, though this is rarely necessary for a short procedure because local variables go out of scope when the procedure ends. Setting a reference to Nothing does not delete the worksheet. It only clears that variable’s reference to the object.
Common errors and how to avoid them
- Using
DimwithoutSet: The declaration does not assign a sheet. Attempting to use an unassigned worksheet variable can produce “Object variable or With block variable not set” (error 91). Assign the object first. - Looking in the wrong workbook: A sheet can exist in one open workbook but not in
ThisWorkbook. Confirm whether the code should useThisWorkbook,ActiveWorkbook, or a specific workbook variable. - Misspelling a sheet name: If the named worksheet is not in the selected workbook, the lookup commonly produces “Subscript out of range” (error 9). Check the tab’s name, including spaces, and check the workbook reference.
- Confusing a chart sheet with a worksheet: A chart sheet is not a worksheet. Use
Worksheetswhen the code needs worksheet tabs, or revise the object type and logic if chart sheets must be handled too. - Relying on the active sheet: Unqualified cell references can act on a different sheet than expected. Use
ws.Range(...)orws.Cells(...)to identify the intended worksheet explicitly.
These checks are especially useful when a macro works on one computer or workbook but fails after a file is renamed, a tab is moved, or another workbook is made active. A worksheet lookup by name is often clear, but it still depends on the exact name being present in the workbook selected by the code.
Safe ways to try worksheet code
Before running a macro that changes workbook contents, save a copy of the workbook. VBA changes cannot be undone with Ctrl+Z, so a backup is the dependable way to preserve the original. The examples above include one that writes to A1; run it only in a workbook where changing that cell is acceptable. The listing example only prints names in the Immediate window.
To inspect or edit VBA in Excel for Microsoft 365 on Windows, open the Visual Basic Editor from the Developer tab’s Visual Basic command. If the Developer tab is not visible, it can be enabled through File > Options > Customize Ribbon. Excel for Mac also includes a Visual Basic Editor, but ribbon and keyboard details can differ by version and keyboard configuration; use the Visual Basic command available in the Mac Excel interface rather than assuming a Windows shortcut will work. Excel for the web can open workbooks containing macros, but it cannot create, run, or edit VBA macros; use the desktop Excel application for those tasks.
Frequently Asked Questions
Does Dim ws As Worksheet create a new worksheet?
No. It declares a variable that can refer to a worksheet. To create a worksheet, VBA needs a separate operation, such as adding an item to a workbook’s Worksheets collection.
Why does VBA require Set for ws?
A worksheet is an object, and Set assigns an object reference to an object variable. It does not assign a cell value or copy a worksheet.
What is the difference between ws and ActiveSheet?ws is a variable whose target your code assigns. ActiveSheet refers to the sheet currently active in the Excel interface. A properly assigned ws can continue to refer to its sheet even when the user activates another tab.
Can I use Dim ws As Worksheet in Excel for the web?
It is VBA syntax, so it must be used in VBA code in desktop Excel. Excel for the web does not run VBA macros; it supports other automation options, such as Office Scripts, which use a different language and model.
Should I use Sheets or Worksheets?
Use Worksheets when you mean worksheet tabs with cells. Use Sheets when you intentionally need to include other sheet types, such as chart sheets, and make sure the variable type and code can handle every item in that collection.
Related
- Data Validation Checks in Excel: Rules and Examples
- Data Validation Checklist for Excel: What to Check
- Conditional Formatting in Microsoft Project: What Works
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Vba loop through rows?Learn how to loop through Excel rows with VBA, find the last row, handle conditions and deletions, and…
- VBA Loop Structures: How to Choose and Use Each TypeVBA has three main loop structures: For...Next for a known number of repetitions, For Each...Next for processing items…
- VBA Find Last Row: Reliable Methods and ExamplesIn VBA, find the last row in a particular column with ws.Cells(ws.Rows.Count, "A").End(xlUp).Row. To find the last row…
- Active Worksheet in VBA: How to Reference ItIn Excel VBA, use the ActiveSheet object to refer to the tab that is active at that moment.…
- Google Sheets Macros: How to Create, Run, and Edit ThemYes. You can create macros in Google Sheets using its built-in recorder: in a desktop web browser, choose…
- Microsoft Access VBA Error Handling: A Practical GuideMicrosoft Access VBA error handling uses the On Error statement to decide what a procedure does when a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.