简体   繁体   English

使用 PowerPoint VBA 打开 Excel 文件,结果不一致

[英]Opening Excel file with PowerPoint VBA, Inconsistent Results

I have a PowerPoint macro that should open an Excel file.我有一个 PowerPoint 宏,它应该打开一个 Excel 文件。

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." “运行时错误‘-2147467259 (80004005)’:object‘工作簿’的‘打开’方法失败。”

The error occurs when trying to run the "Set" line of code.尝试运行“Set”代码行时发生错误。

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):问题是我可以看到代码已成功打开 Excel 文件: 我尝试过的事情(几乎所有可能的组合):

-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... - 将 ReadOnly:= True 添加到两者或其中之一。打开命令,在某一时刻,这给了我一个“自动化错误 - 未指定错误”消息,这是我以前从未见过的......

-Changing the Set line to this (and variations thereof): - 将 Set 行更改为此(及其变体):

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

-Ensuring Excel is completely closed prior to running the code - 确保 Excel 在运行代码之前完全关闭

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.如果您在已打开的工作簿上调用Workbooks.Open可能会导致问题。

So, don't open twice.所以,不要打开两次。 Remove the following line:删除以下行:

xlApp.Workbooks.Open MyFile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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