简体   繁体   English

将Excel公式复制到其他工作簿,而不保留参考

[英]Copying Excel-Formula to different Workbook, without keeping reference

In Workbook1 I have the following formula in Cell AG9 in Worksheet "New Table1" 在Workbook1中,工作表“ New Table1”中的单元格AG9中具有以下公式

=COUNTIF('New Table2'!B:B;"D")

It's supposed to count all the D's in "New Table2" Column B. Using VBA I want to copy the whole Worksheet "New Table1" into a different Workbook(Workbook2), but when I do so, the copied formula in Workbook2 changes to 应该计算“ New Table2”列B中的所有D。使用VBA,我想将整个工作表“ New Table1”复制到另一个Workbook(Workbook2)中,但是当我这样做时,Workbook2中复制的公式更改为

=COUNTIF('C:\\Users\\a.hopf\\Desktop\\[Workbook1.xlsx]New Table2 '!B:B;"D")

How can I prevent the formula from referencing to the original workbook? 如何防止公式引用原始工作簿? The Formula in Workbook2 should also reference to New Table2 in Workbook2. Workbook2中的公式也应引用Workbook2中的New Table2。 I tried using $ to create a absolute reference, but =COUNTIF($'New Table2'!$B:$B;"D") doesn't work. 我尝试使用$创建绝对引用,但是=COUNTIF($'New Table2'!$B:$B;"D")不起作用。

I know I could write the formula into Workbook2 using VBA , but I would prefer to copy it together with the worksheet from Workbook1. 我知道我可以使用VBA将公式写入Workbook2,但我希望将其与Workbook1中的工作表一起复制。

Try copying the worksheet like this: 尝试像这样复制工作表:

Option Explicit

Sub copyFormulasWithoutExternalLinks()

    Dim r1 As Range, r2 As Range

    Set r1 = Workbooks("Book1.xlsm").Worksheets(1).UsedRange
    Set r2 = Workbooks("Book2.xlsm").Worksheets(1).UsedRange

                            'Range("G1") in r1: =COUNTIF('New Table2'!B:B/"D")

    r1.Copy r2              'Range("G1") in r2: =COUNTIF('[Book1.xlsm]New Table2'!B:B/"D")

    '-------------------------------------------------------------------------------------

    Set r2 = Workbooks("Book2.xlsm").Sheets(1).UsedRange    'reset used range in Book2


    Application.DisplayAlerts = False

    r2.Formula = r1.Formula 'Range("G1") in r2: =COUNTIF('New Table2'!B:B/"D")

    Application.DisplayAlerts = True


    '(all formulas in Book2 will be invalid if 'New Table2' sheet is missing)

End Sub

The trick is to use INDIRECT(). 诀窍是使用INDIRECT()。 For example: 例如:

=COUNTIF(INDIRECT("'New Table2'!B:B");"D")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM