I'm looking for a simple solution to exporting a single worksheet containing one loaded Power Query table to a new workbook without the underlying connections and queries.
I think Microsoft changed something in Excel 2019 regarding the behaviour of Power Query tables (ListObject) and the way their connections are being saved between copies. Previously (Excel 2016) when you created a copy either of the table or the worksheet containing the table, only the values and formatting would be preserved and now Excel also duplicates all the queries and connections that are needed to refresh that table. I don't want that - I don't want to expose the Power Query code to anyone I'm sending the data to.
Previously I could use this simple code:
Dim SourceWb As Workbook
Dim SourceSh As Worksheet
Dim TargetWb As Workbook
Dim TargetSh As Worksheet
Set SourceWb = ActiveWorkbook
Set SourceSh = SourceWb.ActiveSheet
SourceSh.Copy
Set TargetWb = ActiveWorkbook
Set TargetSh = TargetWb.ActiveSheet
Application.DisplayAlerts = False
TargetWb.SaveAs SourceWb.Path & "\" & "Copy.xlsx"
TargetWb.Close
Application.DisplayAlerts = True
and now I need to take some extra steps:
Dim SourceWb As Workbook
Dim SourceSh As Worksheet
Dim TargetWb As Workbook
Dim TargetSh As Worksheet
Dim TableCn As WorkbookConnection
Dim TableQr As WorkbookQuery
Set SourceWb = ActiveWorkbook
Set SourceSh = SourceWb.ActiveSheet
SourceSh.Copy
Set TargetWb = ActiveWorkbook
Set TargetSh = TargetWb.ActiveSheet
On Error Resume Next
For Each TableCn In TargetWb.Connections
TableCn.Delete
Next
For Each TableQr In TargetWb.Queries
TableQr.Delete
Next
Application.DisplayAlerts = False
TargetWb.SaveAs SourceWb.Path & "\" & "Copy.xlsx"
TargetWb.Close
Application.DisplayAlerts = True
I know it's not that much more code, but I feel that I may be missing something and maybe the solution can be a little simpler. Is anyone aware of the exact changes made by Microsoft that lead to this behaviour? Were there any changes made in the VBA model that would help with copying/pasting Power Query Tables without preserving the underlying queries?