Search code examples
vbams-project

Setting page layout in MS-project from VBA script


I am working on a script that generates a MS-project plan from inside of excel. All is working fine but I have trouble setting the header and footer. It looks like I need to identify the view name, but I constantly get a runtime error 1101 or some other errors.

I am working on a danish version of MS-project (Side=Page, Sider=Pages) and according to the title of the pagesetup menu my default view is "Gantt-diagram". Also tried with "Gantt Chart" without luck.

Dim pjapp As Object
Dim newproj As Object

Set pjapp = CreateObject("MSProject.application")
pjapp.Visible = True
Set newproj = pjapp.Projects.Add
Set ActiveProject = newproj

' here I want to remove the legend (does not work)
pjapp.FilePageSetupLegendEx Name:="Gantt-diagram", LegendOn:=pjNoLegend

' here I want to set the footer
pjapp.FilePageSetupFooter Alignment:=pjRight
pjapp.FilePageSetupFooter Text:="&[Side] of &[Sider] just some text here"

' setting page to A3 format - this somehow works
pjapp.FilePageSetupPage PaperSize:=8

' here I want to setup the header (does not work)
pjapp.FilePageSetupHeader Name:="Gantt-diagram", Alignment:=pjRight, Text:="My header"

Solution

  • Here are a few things to try:

    • It looks like you are using early binding (otherwise intrinsic constants like pjNoLegend would cause a debug error), so declare the Project object as their native type (e.g. Dim pjapp As MSProject.Application).
    • Use FilePageSetupLegend instead of FilePageSetupLegendEx.
    • Call FilePageSetupHeader using positional arguments rather than the names and skip the view name argument (it will default to the current view). For example: pjapp.FilePageSetupFooter , pjRight, "&[Side] of &[Sider] just some text here"
    • ActiveProject is a reserved word in MS Project so use a different variable name there or just delete that line of code since you already have an object variable, newproj, and it is already the active project.

    Note: To use early binding (easier), include a reference to the Microsoft Project Object Library. To do this, in the VB Editor, go to Tools: References and check the appropriate reference (it might be listed as "Microsoft Office Project Object Library" and will include the version number--I'm using 2013 which is v15.0). Also make sure there aren't any incorrect references checked (e.g. references to the wrong version).

    enter image description here