본문 바로가기
  • You find inspiration to create your own path !
업무 자동화/VBA, VB.NET For Creo

Interface ModelItemOwner - 사용자 정의 함수 만들기

by ToolBOX01 2025. 11. 16.
반응형

◎ 함수(기능)를 사용자가 직접 만들기

  • 안정성 및 신뢰성:
    사용자가 API의 내부 구조를 함부로 변경하거나 잘못 조작하는 것을 막아 시스템의 안정성을 높입니다.
  • 유지보수 용이성:
    API 제공자는 내부 구현 방식을 자유롭게 변경하거나 최적화할 수 있습니다.
    외부에 노출된 인터페이스만 그대로 유지된다면, API를 사용하는 클라이언트 코드는 전혀 영향을 받지 않습니다.
  • 사용 편의성:
    사용자는 복잡한 내부 구조를 알 필요 없이 "이 버튼을 누르면 이 기능이 실행된다"는 것만 알면 되므로,
    API 사용이 훨씬 간단해집니다.

 

모듈, 사용자 정의 함수 동작 순서

 


Sample code

1. 모듈 : CreoConnect

Option Explicit

'// Declare a public variable: Make it accessible throughout the module. //'
Public asynconn As pfcls.CCpfcAsyncConnection
Public conn As pfcls.IpfcAsyncConnection
Public BaseSession As pfcls.IpfcBaseSession

'*******************************************************************************
' Sub: CreoConnect
' Description: Connect to Creo Parametric and initialize the BaseSession object.
'              Checks whether Creo is running, including error handling.
'*******************************************************************************'

Public Sub CreoConnect()

    '// Jump to ErrorHandler label when an error occurs //'
    On Error GoTo ErrorHandler
    
    ' // 1. If a Connection object has not yet been created, a new one is created. //'
    If asynconn Is Nothing Then
        '// Create a CCpfcAsyncConnection object (assign an instance to a variable declared using the New keyword) //'
        Set asynconn = New pfcls.CCpfcAsyncConnection
    End If
    
    ' // 2. Creo Connection Settings: Attempt to connect asynchronously to Creo //'
    ' // Connect(ServerName, Password, WorkingDirectory, Timeout) //'
    ' // Typically, ServerName and Password are set to "", and WorkingDirectory is set to "." (current directory). //'
    ' // Timeout is in seconds. //'
    Set conn = asynconn.Connect("", "", ".", 5) '// 5 second timeout //'
    
    '// 3.Get the BaseSession object //'
    '// If the connection is successful, the conn object contains a BaseSession. //'
    Set BaseSession = conn.Session

    '// If the connection is successful, skip the error handler and exit. //'
    '// Terminates the Sub gracefully, preventing the flow from passing to the ErrorHandler. //' 
Exit Sub 

'// ------------------------------------------------------------------------------- //'
'// Error handling handler //'
ErrorHandler:
    
    '// Error handling when Creo connection library (Toolkit) is not found or Creo is not running //'
    If InStr(Err.Description, "XToolKitNotFound") > 0 Or _
       InStr(Err.Description, "Connect:") > 0 Then '// Errors that may occur in the Connect function //'
        
        MsgBox "오류: Creo Parametric에 연결할 수 없습니다." & vbCrLf & _
               "1. Creo가 실행 중인지 확인하십시오." & vbCrLf & _
               "2. Creo API 환경 설정(Pro/TOOLKIT)을 확인하십시오.", vbCritical, "Creo Connection Error"
               
    Else
        ' // Other general error handling //'
        MsgBox "예기치 않은 오류가 발생했습니다." & vbCrLf & _
               "오류 번호: " & Err.Number & vbCrLf & _
               "오류 내용: " & Err.Description, vbCritical, "General Error"
    End If
    
    '// Initialize global variables when an error occurs (if necessary) //'
    Set conn = Nothing
    Set BaseSession = Nothing
    Set asynconn = Nothing '// Since asynconn can be reused depending on the error type, you can decide whether to keep it or release it depending on your error recovery strategy. //'
    
End Sub

 

2. 사용자 정의 함수 : Function GetModelItemCount ()

' ///////////////////////////////////////////////////////////
' // 이 코드는 BaseSession이 pfcls.IpfcBaseSession 객체로
' // 성공적으로 연결 및 초기화되었다는 가정 하에 작성되었습니다.
' ///////////////////////////////////////////////////////////

Public Function GetModelItems(ByVal ItemType As pfcls.EpfcModelItemType) As Long
    '// 현재 활성화된 Creo 모델에서 지정된 타입의 모델 항목 총 개수를 반환합니다. //'

    '// 변수 선언 //'
    Public Model As pfcls.IpfcModel
    Public ModelItems As pfcls.IpfcModelItems
        
On Error GoTo ErrorHandler

    '// 현재 활성화된 모델 가져오기 //'
    Set Model = BaseSession.CurrentModel
    
    If Model Is Nothing Then
        Debug.Print "경고: 현재 활성화된 모델이 없습니다."
        Exit Function
    End If
    
    '// ModelItemOwner.ListItems() 메서드 사용 //'
    '// Model은 IpfcModelItemOwner를 상속받으므로, ListItems를 직접 호출합니다. //'
    '// 인수로 전달된 ItemType으로 필터링된 항목 목록을 가져옵니다. //'
    Set ModelItems = Model.ListItems(ItemType)

Exit Function

ErrorHandler:
    Debug.Print "오류 발생 (GetModelItemCount): " & Err.Description
    GetModelItemCount = -1 ' 오류 발생 시 -1 반환 등의 오류 표시를 할 수 있습니다.
End Function

 

3. 사용자 개발 프로그램

Sub TestGetModelItemCount()
    
    Dim featureCount As Long
    Dim dimCount As Long
    
    call Connect.CreoConnect
       
    '// 모든 피처 (FEATURE) 개수 세기 //'
    featureCount = GetModelItems(EpfcModelItemType.EpfcITEM_FEATURE)
    
    '// 모든 치수 (DIMENSION) 개수 세기 //'
    dimCount = GetModelItems(EpfcModelItemType.EpfcITEM_DIMENSION)
    
    If featureCount >= 0 Then
        '// 피처가 존재하는 경우 //'
        Debug.Print "현재 모델의 총 피처(FEATURE) 수: " & featureCount & "개"
    ElseIf featureCount = 0 Then
        ' // 피처가 0개인 경우 (정상적으로 목록을 가져왔으나 항목이 없음) //'
        Debug.Print "경고: 현재 모델에는 피처(FEATURE)가 없습니다."
    Else '// featureCount < 0 (오류 발생 시 GetModelItemCount 함수는 -1 또는 -2 반환 가정) //'
        '// 함수 실행 중 오류가 발생한 경우 (예: -1 또는 -2) //'
        MsgBox "피처 수량 확인 중 오류가 발생했습니다. (오류 코드: " & featureCount & ")", vbCritical
        Exit Sub '// 치수 확인을 건너뛰고 종료할 수 있음 //'
    End If
    
    If dimCount >= 0 Then
        '// 치수가 존재하는 경우 //'
        Debug.Print "현재 모델의 총 치수(DIMENSION) 수: " & dimCount & "개"
    ElseIf dimCount = 0 Then
        '// 치수가 0개인 경우 //'
        Debug.Print "경고: 현재 모델에는 치수(DIMENSION)가 없습니다."
    Else '// dimCount < 0 (오류 발생) //'
        '// 함수 실행 중 오류가 발생한 경우 //'
        MsgBox "치수 수량 확인 중 오류가 발생했습니다. (오류 코드: " & dimCount & ")", vbCritical
        Exit Sub
    End If
    
    '// 결과 메시지 출력 예시 //'
    MsgBox "피처 수: " & featureCount & ", 치수 수: " & dimCount, vbInformation, "모델 항목 카운트 결과"

End Sub

자주 사용는 것은 모듈, 사용자 정의 함수로 작성하여, 코드의 재활용을 높입니다.

by korealionkk@gmail.com


반응형