Search code examples
excelvbareferencecell

How do I update formula range in a macro?


I have a formula in A1 that is fed with data from a different workbook. It's only a reference to this other workbook, there aren't any calculations. This second workbook is updated on a monthly basis so the cell I'm interested in referring to is offset one cell to the right each month. How can I write a macro that tells my current formula in A1 to use the same formula but moving it one place to the right? It'd be something like: [Book1]Sheet1!C15 to [Book1]Sheet1!D15. Thanks!


Solution

  • Use Range.Precedents to get the cells a particular Range depends on.

    'get the cell:
    Dim theCell As Range
    Set theCell = ActiveSheet.Range("A1")
    
    'get its first "precedent" Range:
    Dim precedent As Range
    Set precedent = theCell.Precedents(1)
    
    'rewrite the formula, offsetting the precedent by 1 column:
    theCell.Formula = "=" & precedent.Offset(ColumnOffset:=1).Address(External:=True)
    

    Obviously this makes a lot of assumptions and will need to be adjusted to your specific needs, but you don't need to parse any formulas to offset its precedent cells when you're looking at a formula that's simply =SomeCellAddress.