This is probably not the most efficient solution, but it works.
The following code will consolidate my sub projects into a pre-formatted master file. It uses some array variables to capture the required data from each file in turn. All variables are publicly declared in a separate module.
Question: is it necessary to open the sub project files to do this, as this slows the process down somewhat?
Sub Consolidate()
Application.DisplayAlerts = False
DeleteTasks:
' Delete current contents of Master File
For Each Tsk In ActiveProject.Tasks
Tsk.Delete
GoTo DeleteTasks ' Necessary as once the Task is deleted the variable Tsk is set to Nothing and the loop fails
Next
' make sure you've added a reference (Tools>References)
' to "Microsoft Scripting Runtime"
Set fso = New FileSystemObject
Set SourceFolder = fso.GetFolder(SubProjFolderPath)
i = 1 ' count of files in source folder
'build a list of file names
For Each SourceFile In SourceFolder.Files
If Right(SourceFile.Name, 3) = "mpp" Then
strFiles = strFiles & SubProjFolderPath & SourceFile.Name & ListSeparator
' Open each file to capture key data in array variables
FileOpen SourceFile
ReDim Preserve arrPID(i)
ReDim Preserve arrSubNames(i)
arrPID(i) = ActiveProject.ProjectSummaryTask.Text30
arrSubNames(i) = ActiveProject.ProjectSummaryTask.Name
For Each Tsk In ActiveProject.Tasks
Tsk.Text30 = ActiveProject.ProjectSummaryTask.Text30
Next Tsk
FileClose pjSave
iMax = i ' equals the number of files in source folder to be added to master plan
i = i + 1
End If
Next SourceFile
If Len(strFiles) <> 0 Then
'ConsolidateProjects with the file list
strFiles = Left(strFiles, Len(strFiles) - 1)
Application.ConsolidateProjects Filenames:=strFiles, AttachToSources:=False, NewWindow:=False
End If
Application.DisplayAlerts = True
Then I use this code to apply the values to each task in the newly populated Master plan file.
Sub RefreshCustomFields()
' Assign the Project ID from the Sub Project file to the relevant sub project summary task in the new MasterPlan
i = 1
For Each Tsk In ActiveProject.Tasks
TaskName = Tsk.Name
If i > iMax Then End ' to stop the loop after the final Source file name has been matched
If TaskName = arrSubNames(i) Then
Tsk.Text30 = arrPID(i) ' Text30 is set to be the PID
i = i + 1
End If
Next Tsk
DisplayProjectSummaryTask = True
on the subprojects before consolidating (note: I don't think this will work, but worth a try).