2014-10-29 59 views
1

我想將一個表(該表稱爲「Consultations」)導出到Excel,然後打開文件。我正在用一個按鈕做一個表單。此時,我已正確導出文件,但Excel未保持打開狀態。我嘗試使用xlApp.Visible = True,但它僅在導出文件時打開Excel,然後在完成時關閉Excel。將表導出到Excel和打開文件

我需要插入什麼代碼才能保持Excel(和導出的文件)打開?

Private Sub btnExportConsultations_Click() 

Dim curPath As String 
Dim xlApp As Object 

Set xlApp = CreateObject("Excel.Application") 
xlApp.Visible = True 
curPath = CurrentProject.Path & "\Consultations - " & Format(Date, "MM") & "-" & Format(Date, "dd") & "-" & Format(Date, "yyyy") & ".xlsx" 
DoCmd.TransferSpreadsheet acExport, 10, "Consultations", curPath, -1 

End Sub 

回答

3

創建電子表格,然後使用Application.FollowHyperlink在與該文件類型關聯的應用程序---這應該是Excel中打開它。

Private Sub btnExportConsultations_Click() 
    Dim curPath As String 

    curPath = CurrentProject.Path & "\Consultations - " & _ 
     Format(Date, "mm-dd-yyyy") & ".xlsx" 
    DoCmd.TransferSpreadsheet acExport, 10, "Consultations", curPath, -1 
    Application.FollowHyperlink curPath 
End Sub 

注意我也改變了curPath =線。您可以使用一個Format()表達式而不是三個將您的格式化日期轉換爲文件名。

+0

很棒!感謝關於將'curPath ='行更改爲一個表達式的提示。 – user646464 2014-10-30 13:17:15

0

在您使用Excel應用程序對象的Workbooks.Open方法創建的Excel對象中打開工作簿。另外,我會在使用Excel之前導出文件 - 不知道它是否有所作爲,但我認爲代碼至少流動得更好。

Private Sub btnExportConsultations_Click() 

    Dim curPath As String 
    Dim xlApp As Object 

     curPath = CurrentProject.Path & "\Consultations - " & Format(Date,"mm-dd-yyyy") 
     DoCmd.TransferSpreadsheet acExport, 10, "Consultations", curPath, -1 

     Set xlApp = CreateObject("Excel.Application") 
     xlApp.Workbooks.Open(curPath) 
     xlApp.Visible = True 

End Sub