In VBA, Set assigns an object reference to a variable, and it is required whenever the variable is an object type (such as Worksheet, Range, or Workbook). Without Set, VBA throws a runtime error 91: “Object variable or With block variable not set.”
What Does Set Actually Do?
VBA has two kinds of variables: value types (like Long, String, or Boolean) and reference types (objects). When you assign a value to a value variable, you store the data directly. When you assign an object to a variable, you are not copying the object itself—you are storing a reference (a pointer) to the object in memory.
The Set keyword tells VBA that the right side of the assignment is an object, not a value. For example:
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Here, ws now points to the same worksheet object that Sheet1 refers to. Any changes you make through ws affect the actual worksheet.
When Do You Need Set?
You need Set whenever you assign an object to a variable. Common object types include:
Workbook,Worksheet,Range,CellsChart,Shape,ListObjectDictionary,Collection,ArrayList- User-defined class instances (e.g.,
Dim c As New Customerstill requiresSetfor later assignments)
You do not use Set for simple data types:
Dim x As Long
x = 10 ' No Set needed
Also, you do not use Set when calling a method that returns a value (like Function that returns a String), even if the value is an object? Actually, if a function returns an object, you still need Set to capture it. For example:
Dim rng As Range
Set rng = Range("A1") ' Range returns a Range object
If you omit Set in that line, VBA will try to assign the default property of the Range (which is Value), leading to a type mismatch or error.
Common Mistakes and Misconceptions
One frequent error is using Set with a non-object variable:
Dim i As Integer
Set i = 5 ' Error: Object required
Another misconception is that Set creates a copy of the object. It does not—it creates a reference. If you assign one object variable to another with Set, both point to the same object:
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = ThisWorkbook.Sheets(1)
Set ws2 = ws1 ' ws2 now points to the same sheet
Changing ws2.Name changes the sheet’s name, and ws1.Name reflects that change.
Also, do not confuse Set with the Let statement (which is optional and rarely used). In older BASIC, Let was used for value assignments, but in VBA it is implicit.
How to Use Set with New Objects
When you create a new object instance, you must use Set:
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
Or with a class module:
Dim emp As Employee
Set emp = New Employee
If you declare Dim emp As New Employee, VBA automatically creates an instance when you first use it, but it is still good practice to use Set explicitly to avoid hidden instantiations.
Set with With Statements and Loops
Set is often used inside With blocks to keep a reference to an object you are working with repeatedly:
Dim rng As Range
Set rng = Range("A1:B10")
With rng
.Font.Bold = True
.Interior.Color = vbYellow
End With
In loops, you might reassign the object variable each iteration:
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
Debug.Print ws.Name
Next ws
Here, ws is automatically set to each worksheet in the collection—no explicit Set needed because the For Each loop handles it internally.
Set and Memory: Releasing References
Object variables hold references until they go out of scope or are set to Nothing. To explicitly release an object (especially important for large objects or when you want to free memory), use:
Set ws = Nothing
This is not strictly necessary in most cases because VBA’s garbage collection handles it, but it is good practice in long-running macros or when working with COM objects like Excel Application or ADODB connections.
Note: Setting an object variable to Nothing does not destroy the object if other references still exist—it only removes that reference.
Set vs. Let and Default Properties
In VBA, Let is the default assignment operator for values, but it is rarely written explicitly. For objects, Set is mandatory. A classic pitfall is relying on default properties:
Dim rng As Range
Set rng = Range("A1")
Dim val As String
val = rng ' This works because rng's default property is Value
But if you write Set val = rng, you get an error because val is a String, not an object. Conversely, writing Set rng = "A1" fails because a string is not an object.
Set in User-Defined Functions (UDFs)
When you create a custom function that returns an object, you must use Set on the return line:
Function GetRange() As Range
Set GetRange = Range("A1")
End Function
If you omit Set, VBA will try to return the default property (Value), which may cause a type mismatch if the function is declared to return a Range.
Frequently Asked Questions
Why do I get “Object required” error when I use Set?
This error occurs when you try to use Set with a variable that is not declared as an object type, or when the right-hand side of the assignment is not an object. Check that the variable is declared with Dim as an object type (e.g., Dim ws As Worksheet) and that you are assigning an object reference, not a value.
Can I use Set with a variable that is already declared as a specific object type?
Yes, Set is used exactly for that. For example, Dim ws As Worksheet then Set ws = ThisWorkbook.Sheets(1) is correct. The variable type must be compatible with the object you assign.
What happens if I forget Set when assigning a Range?
If you write Dim rng As Range: rng = Range("A1"), VBA will attempt to assign the default property of the Range (which is Value) to a Range variable, causing a type mismatch error. In some cases, if the variable is a Variant, it may store the value instead of the object, leading to subtle bugs.
Is Set required for collections like Dictionary?
Yes, because a Dictionary is an object. You must use Set dict = CreateObject("Scripting.Dictionary") or Set dict = New Dictionary (if you have the reference enabled).
Can I use Set to assign a new object to an existing variable?
Yes, you can reassign an object variable to point to a different object at any time. Just use Set again. The previous reference is released automatically.
Does Set work in Excel for Mac?
Yes, VBA works the same on Mac, and Set is used identically. However, some object libraries may differ slightly (e.g., file paths), but the syntax for Set is universal.
Related
- PL/SQL Queries for Interview: 20+ Real Questions
- Select Each Cell in a Range: Excel Steps
- How to Apply Data Entry: Step-by-Step Guide
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Access VBA MsgBox Constants: Buttons, Icons and ResultsAccess VBA uses the built-in MsgBox function to show a message and, optionally, buttons, an icon, and a…
- Excel Macro Recorder: Can It Repeat Without a Limit?Excel’s Macro Recorder does not have a built-in “repeat forever” setting: it records a set of actions once.…
- Google Sheets Macros: Examples and How to Use ThemGoogle Sheets macros are saved actions you can replay to automate repetitive work, such as formatting a report,…
- VBA Dictionary Exists and Add: How They WorkYes. In a VBA Dictionary, use Exists to check whether a key is already present and Add to…
- VBA InputBox Cancel: Detecting Cancel and Blank RepliesIn VBA, the built-in InputBox function returns an empty string when the user clicks Cancel, but it also…
- Excel VBA Boolean: True, False, and How to Use ThemYes—Excel VBA has a built-in Boolean data type for values that are either True or False. Declare a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.