Suppose that my Excel workbook contains three worksheets called Object1
, Object2
and Calculations
.
- In worksheet
Object1
, cellA1
is calledObject1_Beginning
and contains the value250
. - In worksheet
Object2
, cellB1
is calledObject2_Beginning
and contains the value750
.
In worksheet Calculations
, cell A1
contains a formula of the following form:
=IF(INDIRECT(CONCAT("'Object1'!", ADDRESS(ROW(Object1!Object1_Beginning), COLUMN(Object1_Beginning)))) < 500, 1, 0)
(I do not know why Excel sometimes removes the '
characters when writing the names inside the =ROW()
and =COLUMN()
functions but it works just fine. I also know that using both =INDIRECT()
as well as =CONCAT()
is not actually needed in this case but I have a more complex formula at work where it is required in a similar way as shown in this example.)
Then, I decided to write a macro that could replace the string Object1
in 'Calculations'!A1
’s formula with Object2
so that the result should look like this:
=IF(INDIRECT(CONCAT("'Object2'!", ADDRESS(ROW(Object2!Object2_Beginning), COLUMN(Object2_Beginning)))) < 500, 1, 0)
The macro code used for this purpose is written as follows:
ThisWorkbook.Sheets("Calculations").Range("A1").Formula = Replace(ThisWorkbook.Sheets("Calculations").Range("A1").Formula, "Object1", "Object2", , , vbTextCompare)
However, the result then looks like this:
=IF(@INDIRECT(CONCAT("'Object2'!", ADDRESS(ROW(Object2!Object2_Beginning), COLUMN(Object2_Beginning)))) < 500, 1, 0)
I cannot remove the additional @
character before the =INDIRECT()
function by using the Replace()
function in VBA. In this simple case, the formula still works and can calculate the correct result. Under more complex circumstances, however, this is not the case. Only when I then manually remove all the @
characters, the calculation of the modified formula works correctly.
What can I do? I suppose that it has something to do with the =INDIRECT()
function being nested inside the =IF()
function but I cannot figure out how do fix this issue.