How to add a new column in Microsoft Project from

2019-08-25 07:54发布

问题:

I'm writing a Sub in Excel right now with VBA. I've successfully opened a MS Project project. Now, I want to add a new column in the MS Project file via Excel VBA. How do I do this?

'''vba

Dim MSProject As MSProject.Application
Dim project As MSProject.project

Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook
Set ws = Sheets("Sheet1")
wb.Activate
ws.Select

' Open Microsoft Project project
Set MSProject = CreateObject("MSProject.Application")
With MSProject
    .FileOpen "test.mpp"
    .Application.Visible = True
End With

Set project = MSProject.ActiveProject

' Add column in Project (this syntax does not work)
MSProject.TableEditEx(Name:="test.mpp", TaskTable:=True, _NewFieldName:="JIRA Issue Key", Title:="JIRA Issue Key", Width:=15, _ShowInMenu:=True, _ColumnPosition:=1)

'''

回答1:

  1. Don't use MSProject as a variable name as it the name of the library. Same for project. Typical variable names would be something like prjApp and prj.
  2. Do you have an enterprise field named "JIRA Issue Key"? The field name must be a valid, existing field.
  3. The Name argument in the TableEditEx refers to the name of the table, not the project.
  4. After editing the table, you need to apply changes with TableApply

Here's how the code should look to add an existing field to the default table (Entry) in the default view (Gantt Chart):

prjApp.TableEditEx Name:="Entry", TaskTable:=True, NewFieldName:="Text1", Title:="Custom title here", Width:=15, ShowInMenu:=True, ColumnPosition:=1
prjApp.TableApply "Entry"

See the documentation for more information.