[vba] simple vba code gives me run time error 91 object variable or with block not set

So I have a simple little macro/sub defined when a command button is clicked. The problem is it gives me:

Run Time Error '91' : Object Variable or With Block not Set

My code is:

Dim rng As Range
rng = Sheet8.Range("A12") '<< ERROR here
rng.Value2 = "1"

I just want to set Cell "A12" in Sheet8.

enter image description here

Thanks!

This question is related to vba excel excel-2007

The answer is


You need Set with objects:

 Set rng = Sheet8.Range("A12")

Sheet8 is fine.

 Sheet1.[a1]

Check the version of the excel, if you are using older version then Value2 is not available for you and thus it is showing an error, while it will work with 2007+ version. Or the other way, the object is not getting created and thus the Value2 property is not available for the object.


Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1

below test code for ref.

Sub test()
    Dim rng As Range
    Set rng = Range("A1")
    rng.Value2 = 1
End Sub

Examples related to vba

Copy filtered data to another sheet using VBA Better way to find last used row Check if a value is in an array or not with Excel VBA Creating an Array from a Range in VBA Excel: macro to export worksheet as CSV file without leaving my current Excel sheet VBA: Convert Text to Number What's the difference between "end" and "exit sub" in VBA? Rename Excel Sheet with VBA Macro Extract Data from PDF and Add to Worksheet Quicker way to get all unique values of a column in VBA?

Examples related to excel

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Converting unix time into date-time via excel How to increment a letter N times per iteration and store in an array? 'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data) How to import an Excel file into SQL Server? Copy filtered data to another sheet using VBA Better way to find last used row Could pandas use column as index? Check if a value is in an array or not with Excel VBA How to sort dates from Oldest to Newest in Excel?

Examples related to excel-2007

Declare a variable as Decimal filter out multiple criteria using excel vba Excel Formula which places date/time in cell when data is entered in another cell in the same row Creating a list/array in excel using VBA to get a list of unique names in a column Delete all data rows from an Excel table (apart from the first) Excel formula to get week number in month (having Monday) Run-time error '1004' - Method 'Range' of object'_Global' failed A formula to copy the values from a formula to another column Excel how to find values in 1 column exist in the range of values in another Delete entire row if cell contains the string X