MS Project 宏不会在连续运行中打开 Excel 文件

发布于 2025-01-17 02:37:08 字数 835 浏览 3 评论 0原文

我正在编写一个带有目标开口和 Excel 文件的宏。它在宏的所有其他运行中都能成功运行。下面的代码在第一次运行时成功打开文件,但第二次就不会运行。然后它将在第三次尝试时运行,但不会在第四次尝试时运行。然后重复该循环。

Sub OpenExcelFile()

Set pj = ActiveProject
Set xlApp = New Excel.Application
xlApp.Visible = True
CurrPath = Application.ActiveProject.Path

Dim FD As FileDialog
Set FD = xlApp.FileDialog(msoFileDialogFilePicker)
With FD
    .InitialFileName = "N:\Corporate\P2P"
    .Title = "Select Excel File"
    .Filters.Clear
    .Filters.Add "Excel Files", "*.xlsm*"
    .Show
End With
Dim xlFile As String
xlFile = FD.SelectedItems(1)
MyFileName = xlFile
If MyFileName <> False Then
    Workbooks.Open FileName:=MyFileName
End If


FileNameFromPath = Right(MyFileName, Len(MyFileName) - 
InStrRev(MyFileName, "\"))
Set xlBook = xlApp.Workbooks(FileNameFromPath)
xlBook.Activate
          
End Sub

I am writing a macro with the goal opening and Excel file. It works successfully on every other run of the macro. The below opens the file successfully on the first run, but won't run a second time. It will then run on a third try, but not a fourth. The cycle then repeats.

Sub OpenExcelFile()

Set pj = ActiveProject
Set xlApp = New Excel.Application
xlApp.Visible = True
CurrPath = Application.ActiveProject.Path

Dim FD As FileDialog
Set FD = xlApp.FileDialog(msoFileDialogFilePicker)
With FD
    .InitialFileName = "N:\Corporate\P2P"
    .Title = "Select Excel File"
    .Filters.Clear
    .Filters.Add "Excel Files", "*.xlsm*"
    .Show
End With
Dim xlFile As String
xlFile = FD.SelectedItems(1)
MyFileName = xlFile
If MyFileName <> False Then
    Workbooks.Open FileName:=MyFileName
End If


FileNameFromPath = Right(MyFileName, Len(MyFileName) - 
InStrRev(MyFileName, "\"))
Set xlBook = xlApp.Workbooks(FileNameFromPath)
xlBook.Activate
          
End Sub

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山有枢 2025-01-24 02:37:09

您有一个不合格的 Workbooks.Open 调用。我建议您将以下内容更改

If MyFileName <> False Then
    Workbooks.Open FileName:=MyFileName
End If


FileNameFromPath = Right(MyFileName, Len(MyFileName) - 
InStrRev(MyFileName, "\"))
Set xlBook = xlApp.Workbooks(FileNameFromPath)

为:

If MyFileName <> False Then
    Set xlBook = xlApp.Workbooks.Open FileName:=MyFileName
End If

You have an unqualified Workbooks.Open call in there. I'd suggest you change this:

If MyFileName <> False Then
    Workbooks.Open FileName:=MyFileName
End If


FileNameFromPath = Right(MyFileName, Len(MyFileName) - 
InStrRev(MyFileName, "\"))
Set xlBook = xlApp.Workbooks(FileNameFromPath)

to this:

If MyFileName <> False Then
    Set xlBook = xlApp.Workbooks.Open FileName:=MyFileName
End If
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文