How to preserve a formula's reference to a worksheet when the worksheet is deleted and replaced?

后端 未结 1 343
清酒与你
清酒与你 2020-12-10 09:36

I am the author of an application that before opening an Excel workbook, deletes and recreates some worksheets, like, for example \"Sheet1\" in the example below.

Ot

相关标签:
1条回答
  • 2020-12-10 10:09

    Use Indirect Addressing and Named Ranges

    1) Use phantom cells (i.e Z1...Zn) populated with the text "SheetN!" for each sheet you want to delete.

    2) Define range names for all your externally addressable cells and ranges in those sheets

    3) In your formulas replace the references with "Indirect" and the LITERAL of the named range.

    Example:

    Replace

        =Sum(Sheet1!A:A)   
    

    with

        =SUM(INDIRECT(Z1&"caca"))  
    

    Where "caca" is a Named Range defined in Sheet1 as A:A, and Z1 contains "Sheet1!"

    Another Example:

    Replace

        =Sheet1!A1+Sheet1!A2
    

    with

        =INDIRECT(Z1&"NamedRangeForA1")+INDIRECT(Z1&"NamedRangeForA2")  
    

    Now you can delete the Sheet1 without reference problems.

    You should re-create (in VBA) the Named Ranges when you add your new Sheet1.

    Edit: Answering your comment about Sheets with blanks in name

    In this case you need extra-fu :)

    Use this:

     =INDIRECT("_'_" & Z1& "_'_!_" & "caca")  
    

    The "_" should be removed, as I inserted them there just for ease the visualization of the single and double quotes.

    In the cell Z1 enter the name of Sheet1 without quotes and without exclamation mark (as it is already in the formula).

    HTH!

    0 讨论(0)
提交回复
热议问题