Excel VBA - 打开MS项目文件的代码不起作用



我编写了一些代码来允许我选择一个 MS Project 文件并打开它,但是当我运行代码时,没有任何反应。

零错误,它只是退出,对我在这里做错了什么有什么建议吗?

下面的代码

Sub START()
' MS Project variables 
Dim Proj             As MSProject.Application
Dim NewProj          As MSProject.Project
'File Name Variables
Dim FileOpenType     As Variant
Dim NewProjFileName  As String
Dim NewProjFilePath  As String
Dim NewProjFinal     As String

'Code to find and open project files
Set Proj = CreateObject("MsProject.Application")
MsgBox ("Please Select MS Project File for Quality Checking")
'Select Project File
FileOpenType = Application.GetOpenFilename( _
               FileFilter:="MS Project Files (*.mpp), *.mpp", _
               Title:="Select MS Project file", _
               MultiSelect:=False)
'Detect if File is selected, if not then stop code
If FileOpenType = False Then
   MsgBox ("You Havent Selected a File")
   GoTo EndPoint
End If
'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, ""))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "") + 1)
'Open Project File
Proj.FileOpen NewProjFilePath & NewProjFileName

EndPoint:
End Sub

只是几个注意事项:

首先,由于您使用早期绑定来引用 MS-Project,因此您可以使用 Set Proj = New MSProject.Application 而不是设置 Set Proj = CreateObject("MsProject.Application") 用于后期绑定。

第二:既然Proj被定义为MSProject.Application,为了使MS-Project应用程序可见,使用Proj.Visible = True就足够了。

法典

Option Explicit
Sub START()
' MS Project variables
Dim Proj             As MSProject.Application
Dim NewProj          As MSProject.Project
'File Name Variables
Dim FileOpenType     As Variant
Dim NewProjFileName  As String
Dim NewProjFilePath  As String
Dim NewProjFinal     As String
Set Proj = New MSProject.Application ' since you are using Early binding, you can use this type of setting a new MS-Project instance
MsgBox "Please Select MS Project File for Quality Checking"
'Select Project File
FileOpenType = Application.GetOpenFilename( _
               FileFilter:="MS Project Files (*.mpp), *.mpp", _
               Title:="Select MS Project file", _
               MultiSelect:=False)
If FileOpenType = False Then
   MsgBox "You Havent Selected a File"
   Exit Sub ' <-- use Exit Sub instead of GoTo EndPoint
End If
'Write the FileOpenType variant to two separate strings
NewProjFilePath = Left$(FileOpenType, InStrRev(FileOpenType, ""))
NewProjFileName = Mid$(FileOpenType, InStrRev(FileOpenType, "") + 1)
'Open Project File
Proj.FileOpen NewProjFilePath & NewProjFileName
Proj.Visible = True ' <-- Set MS-Project as visible application
End Sub

通过添加以下行解决,编辑代码以显示

Proj.Application.Visible = True

相关内容

  • 没有找到相关文章

最新更新