问题描述
我尝试使用 Microsoft 项目 VBA 寻找潜在客户,但没有成功我尝试了以下代码,但它给了我 2280 个潜在客户,而我的日程表中的关系总数为 2156 个
Sub NumberofLeads()
Dim Lead As Integer
Dim t As Task
Dim td As TaskDependency
Lead = 0
For Each t In ActiveProject.Tasks
If Not t Is nothing Then
For Each td In t.TaskDependencies 'looping in all the relations of a task
If td.Lag < 0 Then
Lead = Lead + 1
End If
Next
End If
Next t
MsgBox Lead & " Leads exist."
End Sub
解决方法
每个 task dependency 由两个任务组成,因此循环遍历任务然后遍历每个任务的所有依赖项将遇到每个依赖项两次。处理此问题的最佳方法是通过检查 From(或 To)对象的唯一 ID 并进行比较,仅查看任务是前驱(或后继,只需选择一个)的依赖项到当前任务:
Sub NumberofLeads()
Dim Lead As Integer
Dim t As Task
Dim td As TaskDependency
Lead = 0
For Each t In ActiveProject.Tasks
If Not t Is Nothing Then
For Each td In t.TaskDependencies
If td.From.UniqueID = t.UniqueID And td.Lag < 0 Then
Lead = Lead + 1
End If
Next
End If
Next t
MsgBox Lead & " Leads exist."
End Sub
注意:如果除以二似乎比此解决方案更容易,请考虑外部链接的情况。在这种情况下,依赖项只会遇到一次(第二个任务不在 ActiveProject.Tasks
集合中),因此除以二会产生错误的答案。