Home » excel » Excel VBA: Setting a Cell Address to a variable "Object Required Error"

Excel VBA: Setting a Cell Address to a variable "Object Required Error"

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to set a cell address to a variable. And then use that variable to set a cell formula with a referable cell rng i.e. Someone should be able to double click the cell with the formula and see the cell reference of rng rather than the value of the cell rng in the formula. I have the following code:

Dim rng As Range
Dim j As integer 
j = 5
Set rng = ActiveSheet.Cells(j, 1).Address(False, False) ' get error here

ActiveSheet.Cells(1, 15).Formula = "=5*" & rng  

I get this “Object Required Error”. What am i doing wrong?

How to&Answers:

Alternatively, in case you need the rng for anything else, you could do the following

Dim rng As Range
Dim j As integer 
j = 5
Set rng = ActiveSheet.Cells(j, 1)

ActiveSheet.Cells(1, 15).Formula = "=5*" & rng.address

Answer:

Okay, so I believe my issues was that I misunderstood the type that ActiveSheet.Cells(j, 1).Address(False, False) is.

ActiveSheet.Cells(j, 1).Address(False, False) is a String, so you will get an error if you set a Range to a String. Simply changing rng to a String will solve my problem:

Solution:

Dim rng As String
Dim j As integer 
j = 5
rng = ActiveSheet.Cells(j, 1).Address(False, False) ' works now

ActiveSheet.Cells(1, 15).Formula = "=5*" & rng