在不破坏引用的情况下刷新来自 MS Access 查询的 Excel 数据?

Refreshing Excel data from an MS Access query without wrecking references?

我们有一个 Excel 工作簿,其中有很多摘要表,所有这些都引用了我们从 MS Access 查询复制和粘贴的核心 "Data" 选项卡。此数据通过几个 SUMIFS 函数、几个数据透视表引用,并且我们有一个与此选项卡的列关联的名称等。

但我们希望定期刷新这些数据而不破坏一切。是否有 VBA 代码可以从 MS Access 完成此操作?理想情况下,它会做的是清除“数据”选项卡的单元格,然后将查询输出粘贴到那里。我最初考虑过 transferspreadsheet 但这似乎一次替换整张纸并且会破坏所有这些引用。

是否有 "safer" 方法将此数据 refresh/export 添加到 Excel 工作表?

您的用户是否直接与 Excel 中的 DATA 选项卡交互,或者它的存在只是为了将数据提供给其他选项卡以进行计算和表格等操作?因为 Access 不擅长(据我所知)将数据馈送到特定的 Excel 选项卡,但是如果您 运行 一个 OutputTo 命令将查询数据馈送到一个单独的 Excel sheet(与当前 Excel 文件不同的文件名),然后 link 将当前工作簿选项卡中的所有数据添加到同一工作簿的数据选项卡,而不是 link Access 创建的外部数据 sheet。

或者,如果您的用户直接与 DATA 选项卡进行交互,那么 link DATA 选项卡上的数据将传输到由 Access 创建的外部 sheet。

示例函数如下:

Function ExportDataAndOpenExcel()

'1: Delete the old Data sheet if it exists 
   If FileExists("C:\User\Desktop\Data.xlsx") Then
      SetAttr "C:\User\Desktop\Data.xlsx", vbNormal
      Kill "C:\User\Desktop\Data.xlsx"
   End If

'2: Export the data in query to Data.xlsx
    DoCmd.OutputTo acOutputQuery, "MyQuery", acFormatXLSX, _ 
          "C:\User\Desktop\Data.xlsx"

'3: Open the Excel sheet with the tabs and calculations on it
    Dim oApp As Object
       Set oApp = CreateObject("Excel.Application")
       oApp.Visible = True
       oApp.workbooks.Open ("C:\User\Desktop\MyWorkbook.xlsx")

End Function

您可以使用 Range.CopyFromRecordset 方法轻松地将数据复制到 Excel:

Dim excelApp As Object
Set excelApp = CreateObject("Excel.Application")
excelApp.Open strPathToExcelFile
'excelApp.Workbooks(1).Worksheets("Data").UsedRange.ClearContents 'To clear existing content
excelApp.Workbooks(1).Worksheets("Data").Cells(1,1).CopyFromRecordset CurrentDb.QueryDefs("MyQuery").OpenRecordset
excelApp.Workbooks(1).Close
excelApp.Quit