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

眉间皱痕 提交于 2019-11-27 05:53:26

问题


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.

Other worksheets (say Sheet2) in the same workbook may have formulas that refer to the replaced worksheet, like this:

=IF('Sheet1'!A9="","",'Sheet1'!A9)

Unfortunately, the reference in the above formula to Sheet1 is broken when the sheet is replaced, becoming

=IF(#Ref!A9="","",#REF!A9)

Can anyone think of a way to code this formula so it doesn't fail? It could, for example, get the name of the worksheet from a hidden cell in Sheet2 or something?

I just don't know enough about Excel formulas to know what the possibilities are.

TIA


回答1:


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!



来源:https://stackoverflow.com/questions/4070930/how-to-preserve-a-formulas-reference-to-a-worksheet-when-the-worksheet-is-delet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!