Search code examples
excelvbams-project

Excel VBA error when calling MS Project Task's Unique ID


In an Excel worksheet, I am iterating through tasks in a MS Project file with VBA.

I've found that my code works perfectly until I encounter a MS Project task that does not have a name but the error is confusing me. When I delete these unnamed tasks, the error goes away.

I tried adding an if statement: If prj.Tasks(i).UniqueID Is Nothing Then to catch this error but I get a Type mismatch error.

Dim i As Integer
Dim TaskID As Long
Dim ExcelRow As Integer
For i = 1 To prj.Tasks.Count
    TaskID = prj.Tasks(i).UniqueID  'This line is highlighted when I debug
    ExcelRow = GetRowByUniqueID(TaskID)
    Debug.Print ExcelRow

My error is Object variable not set (Error 91). I am confused by this because I was under the impression that all Tasks have a unique ID. When I open my .mpp file in Microsoft Project, I can see that the tasks have no name but have a unique ID in the Unique ID column.

Edit: I just realized it is not an issue with prj.Tasks(i).UniqueID but rather an issue with prj.Tasks(i). How is it possible that this variable is not set when i is within the range of the number of Tasks?


Solution

  • Okay so I just figured it out. Somehow, when I iterate through all the Tasks, some of them are Nothing. I don't really understand why but at the very least, I was able to catch this with an if statement:

    If prj.Tasks(i) Is Nothing Then
        Debug.Print "This is nothing."
    
    Else
        TaskID = prj.Tasks(i).UniqueID
        ExcelRow = GetRowByUniqueID(TaskID)
        Debug.Print ExcelRow
    

    Now, my code does not break at all.