Object variable or With block variable not set
An invalid object variable is being referenced. This error can occur for several reasons:
A variable was declared without specifying a type. If a variable is declared without specifying a type, it defaults to type
Object
.For example, a variable declared with
Dim x
would be of typeObject;
a variable declared withDim x As String
would be of typeString
.Tip
The
Option Strict
statement disallows implicit typing that results in anObject
type. If you omit the type, a compile-time error will occur. See Option Strict Statement.You are attempting to reference an object that has been set to
Nothing
.You are attempting to access an element of an array variable that wasn't properly declared.
For example, an array declared as
products() As String
will trigger the error if you try to reference an element of the arrayproducts(3) = "Widget"
. The array has no elements and is treated as an object.You are attempting to access code within a
With...End With
block before the block has been initialized. AWith...End With
block must be initialized by executing theWith
statement entry point.
Note
In earlier versions of Visual Basic or VBA, this error was also triggered by assigning a value to a variable without using the Set
keyword (x = "name"
instead of Set x = "name"
). The Set
keyword is no longer valid in Visual Basic .Net.
To correct this error
Set
Option Strict
toOn
by adding the following code to the beginning of the file:Option Strict On
When you run the project, a compiler error will appear in the Error List for any variable that was specified without a type.
If you don't want to enable
Option Strict
, search your code for any variables that were specified without a type (Dim x
instead ofDim x As String
) and add the intended type to the declaration.Make sure you aren't referring to an object variable that has been set to
Nothing
. Search your code for the keywordNothing
, and revise your code so that the object isn't set toNothing
until after you have referenced it.Make sure that any array variables are dimensioned before you access them. You can either assign a dimension when you first create the array (
Dim x(5) As String
instead ofDim x() As String
), or use theReDim
keyword to set the dimensions of the array before you first access it.Make sure your
With
block is initialized by executing theWith
statement entry point.
See also
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for