首页 文章

CATIA VBA检查参数存在

提问于
浏览
1

我正在尝试检查部件中是否存在特定参数,如果它不存在,那么我想跳过我的代码的一小部分 . 这是我当前的代码,可以按预期工作:

Dim partDoc As PartDocument
Set partDoc = CATIA.ActiveDocument

Dim ParamV As Parameter
Set ParamV = partDoc.Part.Parameters.Item("ParName")
Dostuffwith ParamV

现在我想在执行最后两行代码之前添加一个检查,它会变成这样的:

Dim partDoc As PartDocument
Set partDoc = CATIA.ActiveDocument

Dim ParamV As Parameter

If partDoc.Part.Parameters.Item("ParName") Exists 
then
Set ParamV = partDoc.Part.Parameters.Item("ParName")
Dostuffwith ParamV
End If

我试过用

On Error goto label1
Set ParamV = partDoc.Part.Parameters.Item("ParName")
Dostuffwith ParamV
label1

但这是不可能的,因为On Error需要以Resume或Resume Next结束 . 在“Dostuffwith ParamV”之后我无法找到使其恢复的方法,它将始终在首先提示错误的代码行中恢复 .

我也试过了

If not partDoc.Part.Parameters.Item("ParName") is nothing 
Then
Set ParamV = partDoc.Part.Parameters.Item("ParName")
Dostuffwith ParamV
End If

但这也会产生错误,因为参数ParName不存在 .

我不知道还能尝试什么,请帮忙 .

2 回答

  • 0

    您可以使用 On Error Resume Next 子句,然后检查 Err.Number 以查看是否发生了任何错误:

    On Error Resume Next
    Err.Clear 'Clear any previous error messages
    Set ParamV = partDoc.Part.Parameters.Item("ParName")
    if Err.Number = 0 then
        'TODO Stuff if Parameter Exists
    else
        'TODO Stuff if parameter does not Exist
    end if
    

    此外,您可以创建一个函数来测试并返回参数 .

    Public Function ParameterExist(byref ParameterCollection as Parameters, byval ParameterName as string, Byref OutputParameter as Parameter) as Boolean
        On Error Resume Next
        Err.Clear
        Set OutputParameter = ParameterCollection.Item(ParameterName)
        if Err.Number = 0 then
            ParameterExist = True
        else
            ParameterExist = False
        end if
    end function
    

    用法:

    dim Param as Parameter
    If ParameterExist(PartDoc.Part.Parameters, "ParName", Param) then
         'Param will hold the parameter object
    end if
    
  • 0

    您使用 On Error Goto <label> 的方法是正确的 . 但是您需要重置错误处理程序,以便在出现其他错误时不会跳转到标签 . 你可以使用:

    On Error GoTo label1
        Set ParamV = partDoc.Part.Parameters.Item("ParName")
        On Error GoTo 0        ' reset the error handler upon success
        Dostuffwith ParamV
        GoTo label 2
    label1:
        On Error GoTo 0        ' reset the error handler after an error
    label2:
    

    另一种方法是使用错误处理的resume方法:

    On Error Resume Next
        Set ParamV = partDoc.Part.Parameters.Item("ParName")
        MyErrNumber = Err.Number
        On Error GoTo 0   ' Reset error handling
        If MyErrNumber <> 0 Then GoTo label1
        Dostuffwith ParamV
    
    label1:
    

相关问题