Excel VBA – 打开MS Project文件的代码不起作用

我写了一些代码,让我select一个MS项目文件,并打开它,但是当我运行的代码,没有任何反应。

零错误,它只是退出,任何build议与我在这里做错了吗?

下面的代码

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 

只是几个注意事项:

首先 ,因为您正在使用Early Binding来引用MS-Project ,所以您可以使用Set Proj = New MSProject.Application ,而不是设置用于Late Binding的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