Thursday, 17 March 2016

How to use cell contents as inputs for range formulas in Excel VBA?

Excel VBA range formula is something like Sheet2.Range("A1").value.
You can, for example, refer to this address and change the value in that cell.
Now what I am looking for is to build this formula by using the contents of two cells; one cell says "Sheet2" and the other says "A1". How can I refer to these two cells in a formula so that it works the same way?



I have tried various dims and now end up without an error but not with the desired result. The current formula simply returns "Sheet2.Range("A1").value instead of its contents.



Sub AddressInCells()

'This is just for one reference. In reailty there is a table of references to loop through.
'For this example cell A1 in Sheet2 = "Text to take to sheet1"

Dim SheetSel As String
Dim CellSel As String
Dim ReferSel As String

With Sheet1

SheetSel = Cells(1, 1).Value

CellSel = Cells(1, 2).Value

ReferSel = SheetSel & ".range(" & Chr(34) & CellSel & Chr(34) & ").value"

MsgBox ReferSel

Sheet1.Range("D1").Value = ReferSel 'Results in "Sheet2.range("A1").value
Sheet1.Range("D2").Value = Sheet2.Range("A1").Value 'Results in Text to take to sheet1'

End With


End Sub


The expected result is that the formula works the "usual" way. It now simply returns a string.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...