如何在VBA中自定义自定义域公式?解决宏执行报错问题
Hey there! Let's break down what's going on with your VBA code for modifying custom fields in Project.
First, that "External name not defined" error for [% Complete] is happening because you're treating it like a VBA variable instead of part of the custom field formula string. [% Complete] is a built-in Project task field, so it needs to live inside the formula text you pass to CustomFieldSetFormula, not get referenced directly in your VBA code.
Let's look at a common mistake that causes this. Suppose your original code looked something like this:
Dim maxUID As Integer maxUID = ' Your dynamic value here CustomFieldSetFormula FieldID:=pjCustomTaskText1, Formula:="IIf(UID=" & maxUID & ", " & [% Complete] & ", 0)"
Here, VBA tries to interpret [% Complete] as a variable (which doesn't exist), hence the error.
The fix is simple: keep [% Complete] inside the formula string instead of concatenating it as a separate "variable". Here's the corrected version:
Dim maxUID As Integer ' Replace this with your actual logic to get the dynamic maxUID (e.g., from a task or calculation) maxUID = ActiveProject.Tasks.Max("UID") ' Example: Grab the highest task UID in the project ' Properly construct the formula string with [% Complete] as part of it CustomFieldSetFormula FieldID:=pjCustomTaskText1, _ Formula:="IIf(UID=" & maxUID & ", [% Complete], 0)"
Now, if your second line is still throwing errors after this fix, let's check a few things:
- Make sure
maxUIDis actually getting a valid value. If it's empty, zero, or a value that doesn't match any task UID, Project might reject the formula. - Double-check the
FieldIDyou're using. If you're modifying a resource custom field instead of a task one, you need to use something likepjCustomResourceText1instead. - Verify the formula syntax is valid in Project. The
IIffunction needs three arguments: a condition, the value if true, and the value if false—your structure looks right, but make sure there are no typos (like misspellingUID).
That should resolve the "External name not defined" error and get your dynamic maxUID working correctly.
内容的提问来源于stack exchange,提问作者Andre Davis

