user10171431
user10171431

Reputation: 61

Excel VBA: Formula with reference to cell in another worksheet (variable)

I am trying to create a macro that links a cell from another worksheet (this is stored as a variable called SheetName). The user is prompted with an Input box to select a cell. I would like to have a cell in another worksheet reference to the selected cell.

Here is the relevant code:

Dim WorkRng As Range
    Total1 = "Select Total cell"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", Total1, WorkRng.Address, Type:=8)
    Worksheets("WorksheetA").Range("C6").formula = "=" & 'SheetName.Name' & "!" & WorkRng.Address

The last line is where I am running into object errors. Any help is greatly appreciated!

Upvotes: 1

Views: 16585

Answers (2)

user4039065
user4039065

Reputation:

Try,

Worksheets("WorksheetA").Range("C6").formula = _
   "='" & SheetName.Name & "'!" & WorkRng.Address

'note the quote here "='" and here "'!"

Upvotes: 2

QHarr
QHarr

Reputation: 84465

Where is sheetname defined? It then needs to be concatenated into the string

DIm SheetName As Worksheet
Set SheetName = Worksheets("Sheet2")

formula then

"=" & SheetName.Name  & "!" & [A1:B2].Address

Upvotes: 1

Related Questions