每次将访问查询导出到同一个工作表

时间:2015-02-18 12:20:38

标签: excel vba excel-vba ms-access access-vba

我有一个带有命名工作表的“Excel二进制工作簿”和一个MS ACCESS,其查询名称与工作簿工作表相同。

例如,我有一个像“CustomersData”这样的表,并且有一个名为相同的查询。

我的问题是当我运行此代码时,它将查询数据导出到“CustomersData1”而不是“CustomersData”

DoCmd.TransferSpreadsheet acExport, 9, xQuery, strFilePath, True, xSheet

我打算在导出数据之前编写首先删除工作表的函数,但是我在同一工作簿中有另外的工作表可以引用这些工作表。

我的代码:

Public Function Export_To_Excel()
On Error GoTo Export_To_Excel_Err

Dim rs As DAO.Recordset
Dim xQuery As String
Dim strPath As String
Dim i As Long

Set rs = CurrentDb.OpenRecordset("SELECT * FROM Export_Specs")

strPath = "D:\Path\To\File.xlsb"

i = 0

If Not (rs.EOF And rs.BOF) Then
        rs.MoveFirst
    Do Until rs.EOF = True
            xQuery = rs("Query_Name")
            DoCmd.TransferSpreadsheet acExport, 9, xQuery, strPath, True
            i = i + 1
        rs.MoveNext
    Loop
Else
    MsgBox "No queries found to export.", vbCritical, "Getting Queries"
End If

MsgBox "Finished. (" & i & ") Queries were exported successfully to " & strPath, vbInformation, "Exporting Data.."


rs.Close
Set rs = Nothing

Export_To_Excel_Exit:
    Exit Function

Export_To_Excel_Err:
    MsgBox Error$
    Resume Export_To_Excel_Exit
End Function

1 个答案:

答案 0 :(得分:0)

我猜测以下替换现有代码应该可以解决问题

DoCmd.TransferSpreadsheet acExport, 9, xQuery, strPath, True, "SheetName!A1:Z200"