Home » excel » vba – command to display Excel after saving

vba – command to display Excel after saving

Posted by: admin May 14, 2020 Leave a comment

Questions:

This is the vba Command that I am using to make a spreadsheet and save it:

DoCmd.TransferSpreadsheet acExport, , “query_alldata1”, “C:\All_Data_2014.xlsx”, True

I also want it to open or display automatically on the screen. I would appreciate any guide.

This is how my subroutin looks like:

Private Sub btnAlldatagen_Click()
On Error GoTo Err_btnAlldatagen_Click
Dim stDocName As String

stDocName = "query_alldata1"

DoCmd.TransferSpreadsheet acExport, , "query_alldata1", "C:\All_Data_2014.xlsx", True


'Workbooks.Open "C:\All_Data_2014.xls"
MsgBox ("Preparing all Data Report")
Exit_btnAlldatagen_Click:
Exit Sub
Err_btnAlldatagen_Click:
MsgBox Err.Description
Resume Exit_btnAlldatagen_Click

End Sub

I am using Workbooks.open command but it does not open the worksheet.

How to&Answers:

Oh, this one is easy.

After

DoCmd.TransferSpreadsheet acExport, , "query_alldata1", "C:\All_Data_2014.xlsx", True

Place:

Dim xl As Object
Set xl = CreateObject("Excel.Application")

With xl
  .Visible = True
  .Workbooks.Open ("C:\All_Data_2014.xlsx")
  '.Do other things with excel here

  '.Workbooks("Test1.xlsm").Close , False '<-- Uncomment to close workbook
  '.Quit '<-- Uncomment to close Excel
End With

'Set xl = Nothing <-- Uncomment to set Excel to Nothing

Answer:

You can add a reference to the Excel runtime library (Microsoft Excel * Object Library), and work with Excel VBA.

Dim xlApp as Excel.Application
Set xlApp = New Excel.Application

xlApp.Workbooks.Open("C:\All_Data_2014.xlsx")
xlApp.Visible

Set xlApp = Nothing

IF you are planning on doing this multiple times, you should make sure to create the xlApp variable once at the beginning of your code, since opening Excel is slow.