VBA:如何在同一个Excel实例中将两个查询导出到Excel?

时间:2016-10-04 23:42:14

标签: excel access-vba

在MS Access中,我有VBA代码,可以创建两个电子表格,然后打开它们。但是,我的代码会在Excel的不同实例中打开这些电子表格。电子表格相互引用,因此需要在同一实例中打开才能正常工作。从桌面手动打开文件(在单个实例中)可以正常工作(电子表格可以在其合作伙伴中查找数据)。

如何让他们在同一个实例中打开?

DoCmd.OutputTo acOutputQuery, "CrossTab", "ExcelWorkbook(*.xlsx)", "C:\Users\10331654\Desktop\CrossTab.xlsx", True, "", , acExportQualityPrint
DoCmd.OutputTo acOutputQuery, "MyQuery", "ExcelWorkbook(*.xlsx)", "C:\Users\10331654\Desktop\MyQuery.xlsx", True, "", , acExportQualityPrint

1 个答案:

答案 0 :(得分:1)

好的 - 找到了答案。您必须手动创建excel实例,然后在其中打开工作表:

        Dim ApXL As Object
        Dim xlWBk1 As Object
        Dim xlWBk2 As Object

DoCmd.OutputTo acOutputQuery, "CrossTab", "ExcelWorkbook(*.xlsx)", "C:\Path\To\File1", False, "", , acExportQualityPrint
DoCmd.OutputTo acOutputQuery, "MyQuery", "ExcelWorkbook(*.xlsx)", "C:\Path\To\File2", False, "", , acExportQualityPrint

Set ApXL = CreateObject("Excel.Application")
            Set xlWBk1 = ApXL.Workbooks.Open(C:\Path\To\File1)
            Set xlWBk2 = ApXL.Workbooks.Open(C:\Path\To\File2)