Reputation: 117
In Workbook1 I have the following formula in Cell AG9 in Worksheet "New Table1"
=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
=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. I tried using $ to create a absolute reference, but =COUNTIF($'New Table2'!$B:$B;"D")
doesn't work.
I know I could write the formula into Workbook2 using VBA , but I would prefer to copy it together with the worksheet from Workbook1.
Upvotes: 1
Views: 1555
Reputation: 907
The trick is to use INDIRECT(). For example:
=COUNTIF(INDIRECT("'New Table2'!B:B");"D")
Upvotes: 0
Reputation: 10715
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
Upvotes: 1