Excel VBA - 打开MS Project文件无效的代码

时间:2017-10-25 03:46:47

标签: excel vba excel-vba ms-project

我编写了一些代码,允许我选择一个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

2 个答案:

答案 0 :(得分:1)

只是几个笔记:

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

答案 1 :(得分:0)

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

builtin/apply.c