Make an Index/Match formula dynamic in VBA

anglais428

Well-known Member
Joined
Nov 23, 2009
Messages
634
Office Version
  1. 2016
Platform
  1. Windows
Hi,

I have the following line of code which is taken from a recorded macro and works:

ActiveCell.FormulaR1C1 = _
"=INDEX(INDIRECT(""'""&RC10&""'!""&RC11),MATCH(RC[-4],INDIRECT(""'""&RC10&""'!$A$3:$A$100""),0),MATCH(RC[1],INDIRECT(""'""&RC10&""'!$D$2:$N$2""),0))"

What I would like to do is edit the $A$3:$A$100 range to make it dynamic. The same with the $D$2:$N$2 range.
I was trying to do this using Cells(3,1) etc. so that I could then swap out the numbers (e.g. 3 and 1) with stored variables, allowing the formula to be dynamic, but I keep running into errors.

Any help would be greatly appreciated.
 

Excel Facts

Repeat Last Command
Pressing F4 adds dollar signs when editing a formula. When not editing, F4 repeats last command.
Keep in mind that when entering a formula like that, it's just a long string. You can manipulate it in lots of ways. For example:

Code:
    rng1 = "$A$3:$A$100"
    rng2 = "$D$2:$N$2"
    ActiveCell.FormulaR1C1 = _
               "=INDEX(INDIRECT(""'""&RC10&""'!""&RC11),MATCH(RC[-4],INDIRECT(""'""&RC10&""'!" & _
               rng1 & """),0),MATCH(RC[1],INDIRECT(""'""&RC10&""'!" & rng2 & """),0))"
You can define rng1 and rng2 in lots of ways:

rng1 = Cells(3,1)

rng1 = Range("A3:A100").Address(0,1,1,0)

rng1 = Replace("$A$3:$A$100", "3", "4")

and many others.

One thing to keep in mind is that you're mixing the R1C1 and A1 types of references in the same formula. Excel can usually figure it out, but not always.
 
Upvote 0

Forum statistics

Threads
1,214,576
Messages
6,120,354
Members
448,956
Latest member
Adamsxl

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top