简体   繁体   中英

Opening Excel file with PowerPoint VBA, Inconsistent Results

I have a PowerPoint macro that should open an Excel file.

Public Sub SortList()

Dim MyFile as String
Dim xlApp as Object
Dim xlWorkBook as Object
Set xlApp = CreateObject("Excel.Application")

With Application.FileDialog(msoFileDialogOpen)
    .AllowMultiSelect = False
    .Show
    MyFile = SelectedItems(1)
End With

xlApp.Visible = True
xlApp.Workbooks.Open MyFile
Set xlWorkBook = xlApp.Workbooks.Open(MyFile)

This code was previously working with no errors. However, I have started receiving the error message

"Run-time error '-2147467259 (80004005)': Method 'Open' of object 'Workbooks' failed."

The error occurs when trying to run the "Set" line of code.

The issue is that I can see that the code is successfully opening the Excel file: Things I have tried (in about every possible combination):

-Changing the code to this (I thought maybe the program was trying to open the file twice):

xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open(MyFile)

-Adding ReadOnly:= True to both or either.Open command, at one point this gave me an "Automation error- unspecified error" message which I have never seen before...

-Changing the Set line to this (and variations thereof):

xlApp.Workbooks.Open MyFile
Set xlWorkBook = xlApp.Workbooks(Dir(MyFile))

-Ensuring Excel is completely closed prior to running the code

The frustrating aspect is that this code worked perfectly last week, so I'm also at a loss as to why it would suddenly stop working. Any assistance would be greatly appreciated.

Workbooks.Open can cause issues if you call it on an already open workbook.

So, don't open twice. Remove the following line:

xlApp.Workbooks.Open MyFile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM