본문 바로가기
  • 환영 합니다 ! Welcome!
VBA For Creo

VBA Fundamentals #2

by ToolBOX01 2020. 11. 29.
반응형

VBA는 계층적 구조의 개체를 사용하여 프로그램을 개발 합니다. Creo의 "부모 /자식" 관계로 이해 하십시요

[ 계층적 개체 ]

 

Option Explicit
Sub CreoExecution()

    Dim asynconn As New pfcls.CCpfcAsyncConnection
    Dim conn As pfcls.IpfcAsyncConnection
    Set conn = asynconn.Start("C:\PTC\Creo 8.0.6.0\Parametric\bin\parametric.bat", "")
        
End Sub

위 코드를 실행 하면 Creo를 실행 할수 있습니다. Creo Parametric에 대한 비동기 연결을 설정하는 것을 목표로 합니다.
각각의 함수의 역활은 아래와 같습니다

1) Option Explicit: 
이 문장은 변수를 선언하지 않고 사용하는 것을 방지하기 위한 VBA의 필수 옵션입니다. 
변수를 명시적으로 선언하도록 강제합니다.

2) pfcls.CCpfcAsyncConnection

 Creo와 VBA 스크립트 간에 비동기적인 작업을 처리하기 위해 사용될 수 있습니다. 비동기 연결은 일반적으로 오래 걸리거나 블로킹되지 않고 백그라운드에서 실행되어 다른 작업을 계속할 수 있는 상황에서 유용합니다.
이 클래스는 Creo Parametric과 비동기적으로 통신하기 위한 기능을 제공합니다.
Creo VBA 스크립트를 작성하려는 경우 pfcls.CCpfcAsyncConnection을 사용하여 비동기적 작업을 처리하는 데 도움을 줄 수 있습니다. 이를 사용하면 한 작업이 완료될 때까지 다른 작업을 수행할 수 있으므로 작업 효율성을 높일 수 있습니다.

비동식적이란?
- 비동기식(Asynchronous) 프로그래밍은 작업이 다른 작업의 완료를 기다리지 않고 병렬로 진행되는 프로그래밍 방식을 말합니다. 이는 일반적으로 작업이 완료될 때까지 기다리지 않고, 대신에 작업이 백그라운드에서 비동기적으로 실행되며, 결과가 나중에 콜백 함수나 이벤트 핸들러를 통해 처리됩니다.

3) IpfcAsyncConnection

비동기 연결은 일반적으로 프로그래밍에서 작업이 백그라운드에서 수행되거나 동시에 여러 작업이 처리될 수 있는 상황을 지원하는 데 사용됩니다.Creo VBA를 사용하는 경우, IpfcAsyncConnection을 사용하여 Creo와 연결하고 비동기 작업을 수행하는 것이 가능할 것입니다. 예를 들면, Creo 모델을 생성, 수정, 분석하는 동안 사용자는 다른 작업을 계속할 수 있을 것입니다.

 3) CCpfcAsyncConnection.Start 메서드 (Function) 

Set conn = asynconn.Start("C:\PTC\Creo 8.0.6.0\Parametric\bin\parametric.bat", "")
위 코드에서 "asynconn" 변수는 "CCpfcAsyncConnection" 함수 입니다. 이것은 비동기 연결을 시작하는 함수입니다.

Function : CCAsyncConnection.Start (CmdLine as String, TextPath as String [optional]) as IpfcAsyncConnection

CmdLine
Creo Parametric을 시작하는 데 사용되는 시작 명령, 배치 파일 또는 스크립트 파일의 전체 경로입니다.

TextPath
메시지 및 메뉴 파일이 보관되는 경로입니다. 외부 메시징이나 메뉴가 필요하지 않은 경우 null을 전달합니다.

이 메서드를 사용하면 비동기 연결을 설정하고 해당 연결을 활성화하여 작업을 백그라운드에서 실행할 수 있습니다. 


IpfcAsyncConnection 개체를 사용하여 Creo를 ShotDown 합니다.

Option Explicit
Sub CreoShotDown()

    Dim asynconn As New pfcls.CCpfcAsyncConnection
    Dim conn As pfcls.IpfcAsyncConnection
    
    conn.End

        
End Sub

■ IpfcBaseSession / IpfcSession


IpfcBaseSession 클래스는 Creo Parametric 세션에 대한 기본적인 인터페이스를 제공합니다. Creo Parametric의 실행 및 제어, 모델 열기/저장, 파트/어셈블리 조작, 기하학적 작업, 설정 관리 등의 작업을 수행하는 데 사용됩니다. IpfcBaseSession 클래스는 Creo Parametric의 시작과 종료, 모델과 파트 관리, 세션 설정 등에 대한 메서드와 속성을 제공합니다.

IpfcSession은 PTC Creo Parametric의 VBA 환경에서 사용되는 중요한 클래스입니다. 이 클래스는 Creo Parametric 세션을 나타내며, Creo Parametric 모델을 조작하고 모델 관리 작업을 수행하는 데 사용됩니다. IpfcSession 클래스는 Creo Parametric과 상호작용하며 모델 열기/저장, 파트/어셈블리 조작, 기하학적 작업, 설정 관리 등 다양한 작업에 필요한 인터페이스와 메서드를 제공합니다.  "IpfcBaseSession" 클래스와 차이점은 "UI"를 사용 하는것 입니다.

IpfcBaseSession.CreateAssembly는 Creo Session에 새로운 어셈블 파일을 생성 합니다 

Option Explicit
Sub CreateAssemble()

    Dim asynconn As New pfcls.CCpfcAsyncConnection
    Dim conn As pfcls.IpfcAsyncConnection
    Set conn = asynconn.CONNECT("", "", "", 5)
    Dim BaseSession As pfcls.IpfcBaseSession
    Set BaseSession = conn.session
    
    Dim NewAssemble As IpfcAssembly
    Set NewAssemble = BaseSession.CreateAssembly("korea005.asm")
        
End Sub

"korea005.asm" 파일이 "Session - 메모리(?)"에 생성됩니다.

[ 세션중 - 어셈블 파일 생성 ]


■ IpfcBaseSession / IpfcSession  사용 예제 

▷  IpfcBaseSession 사용 예제 - Session으로 모델 가져오기

 

IpfcBaseSession 개체 : [Function] RetrieveModel

IpfcBaseSession 개체로 하드 디스크에 있는 Creo 파일을 Creo Session으로가져오는 함수 입니다. (작업 폴더에서 Creo Parametric 세션으로 지정된 모델을 읽어들입니다.) 이 함수는 Creo 화면에 표시되지 않습

tool-2020.tistory.com

 

▷   IpfcBaseSession 사용 예제 -  Sub ChangeDirectory

 

IpfcBaseSession 클래스 이해 #1 - Sub ChangeDirectory

■ Creo VBA 두번째 최상위 포식자(?) IpfcBaseSession 이 개체는 Creo Parametric 세션에 대한 정보를 정의합니다. 현재 활성화된 모델을 연결 합니다. 변수는 "IpfcBaseSession" 개채로정의 합니다. IpfcBaseSession.C

tool-2020.tistory.com

 

▷   IpfcBaseSession 사용 예제 - Function 이해

 

IpfcBaseSession 이해 #2 - Function GetConfigOption

Function 프로시져는 프로그램을 실행 하고 Return 값을 줍니다. IpfcBaseSession Function : GetConfigOption (Name as String) as String [optional] 지정된 구성 파일 옵션에 대한 현재 값을 검색합니다. 이 함수가 반환하

tool-2020.tistory.com

 

▷   IpfcBaseSession 사용 예제 - sub 이해

 

IpfcBaseSession #3 - sub (프로시저)

■ sub EraseUndisplayedModels () - Creo Parametric 창에서 사용되지 않는 모델을 session에서 지웁니다. (Creo window 리스트에 표시되지 않으면 session에서 지워 집니다.) Sub EraseModels_Undisplayed() Dim asynconn As New pfcl

tool-2020.tistory.com

 

▷   IpfcBaseSession 사용 예제 - 폴더

 

IpfcBaseSession #4 - 지정된 디렉토리의 파일 목록 찾기

 

tool-2020.tistory.com

 

▷   IpfcBaseSession 사용 예제 - Session에 있는 모델들 이름 모두 표시

 

IpfcBaseSession # 5 Session에 있는 모델들 이름 모두 표시

Creo Session 안에 있는 creo 파일 이름을 표시 합니다. 번호와 함께 파일이름, 총 파일 수량 이 표시 됩니다, 만일 Creo Session 안에 creo 파일이 없으면 파일 수량은 "0"으로 표시 됩니다. ■ 소스 코드 Sub

tool-2020.tistory.com

 


▷  IpfcSession 사용 예제

 

IpfcSession #1 : 화면 UI를 이용하여 파일 오픈 하기

Creo 화면에서 Open 대화 상자를 통해 파일 이름을 선택 기능 입니다. 클래스 IpfcSession , 함수 UIOpenFile를 사용 합니다. Return 값은 string 이며 폴더 이름 및 Creo 파일명을 함께 반환 합니다. Return 예시)

tool-2020.tistory.com

 

 

IpfcSession #2 : 함수 UISaveFile, 저장 대화 상자 표시

UI를 통해 현재 활성화된 파일을 선택 하면, 파일 이름을 String으로 Return 한다. 반화된 값 예시 :) "C:\Users\Public\Documents\japan.prt.3" 하드 디스크에 저장 하는 기능은 없다. 객체 타입 "IpfcModel"의 변수

tool-2020.tistory.com


■ 예제 

VBA 프로그램으로  하드디크에 저장된 "korea.prt" 파일을 읽고, 매개변수 실수 타입 매개변수 이름 "LENGTH"를 읽고 , 50.5 값을 입력하는 프로그램 입니다. 다음과 같은 순서로 프로그램을 코딩 합니다.

1. Session으로 "korea.prt" 파일 읽기
2. 파일에 저장된 매개변수 읽기
3. 파일에 저장된 LENGTH 매개변수 확인
5. 매개 변수 값 "50.5" 입력

1단계 : Creo와 VBA 프로그램 연결         
대부분의 VBA 프로그램은 IpfcBaseSession 클래스로 부터  상속 하여 시작 합니다. 아래 코드는 Creo와 VBA를 연결 하는 코드 입니다. 또한 오류 가 발생하면 에러 코드를 표시하는 코드가 있습니다.


Sub Parameter01()
    On Error GoTo RunError    
        Dim asynconn As New pfcls.CCpfcAsyncConnection
        Dim conn As pfcls.IpfcAsyncConnection
        Dim session As pfcls.IpfcBaseSession
    
        Set conn = asynconn.Connect("", "", ".", 5)
        Set session = conn.session
    
       

    	conn.Disconnect (2)

	RunError:
    
        If Err.Number <> 0 Then
            MsgBox "Process Failed : Unknown error occurred." + Chr(13) + _
                    "Error No: " + CStr(Err.Number) + Chr(13) + _
                    "Error: " + Err.Description, vbCritical, "Error"

            If Not conn Is Nothing Then
                If conn.IsRunning Then
                    conn.Disconnect (2)
                End If
            End If
        End If

End Sub

 

2단계 : LOCAL 하드 디스크의 Creo Part 파일 읽기

          엑셀의 폴더 및 CREO 파일 이름을 입력합니다. 작업 공간의 입력 창 주소는 cells (4, "E") 이고,
          Creo 파일 이름 입력 창 주소는 cells (5, "E") 입니다. VBA 프로그램은 작업 공간을 변경 하고, Creo Window에
          입력한 모델을 찾아 파일을 표시 합니다.

[ 사용자 입력 창 ]
[ Creo Model ]

    Dim oForderName As String
    oForderName = cells (4, "E")
    session.ChangeDirectory (oForderName)
    
    Dim oCreofileName As String
    oCreofileName = cells (5, "E")
    
    Dim oModelDescriptorCreate As New CCpfcModelDescriptor
    Dim oModelDescriptor As IpfcModelDescriptor
    Set oModelDescriptor = oModelDescriptorCreate.Create(EpfcMDL_PART,oCreofileName, Null)
    
    Dim oModel As pfcls.IpfcModel
    Set oModel = session.RetrieveModel(oModelDescriptor)

    Dim oWindow As pfcls.IpfcWindow
    Set oWindow = session.OpenFile(oModelDescriptor)
        oWindow.Activate

만일 Creo ASSEMBLE 파일을 읽으려면 어떻게 해야 할까요? "EpfcMDL_PART"를 변경 합니다. 설명자의 유형은 아래와 같습니다

EpfcMDL_ASSEMBLY    - An assembly.
EpfcMDL_PART        - A part.
EpfcMDL_DRAWING     - A drawing.
EpfcMDL_2D_SECTION  - A two-dimensional section.
EpfcMDL_LAYOUT      - A layout.
EpfcMDL_DWG_FORMAT  - A drawing format.
EpfcMDL_MFG         - A manufacturing model.
EpfcMDL_REPORT      - A report.
EpfcMDL_MARKUP      - A drawing markup.
EpfcMDL_DIAGRAM     - A diagram.
EpfcMDL_UNSPECIFIED - Not specifying a particular model type
EpfcMDL_CE_SOLID    - Layout model; NOTE: this type is read-only, passing it back to Creo may lead to unpredictable behavior.
EpfcMDL_CE_DRAWING  - Reserved for internal use.
EpfcModelType_nil   - Use this enumerated value to represent "null" passed to optional properties or method arguments.

 

3단계 : Creo 파일의 매개변수 검색
          Creo 파일의 매개변수에서 "LENGTH" 매개 변수를 검색하고 값 50.5로 변경 합니다. 다음과 같은 동작 순서가
          정의 되어야 합니다

          1) "LENGTH" 매개 변수가 있는지 검색
          2) 존재 한다면 값만 변경
          3) 존재 하지 않는다면, 매개 변수 "LENGTH" 추가 및 값 입력
         

          코드가 미완성 되어 추가 하지 않았습니다.

[ 길이 값 입력 ]


■ 예제 파일 사용 주의 사항

1. 현재 작업 공간에  "korea.prt" 만들고 저장 합니다. 단, 매개변수는 모두 지웁니다
    (ez_param4와 동일한 매개변수가 존재 한다면, 오류가 발생합니다.)
2. Creo Session에 모든 Creo 파일을 지웁니다.
3. VBA 프로그램을 실행 하면, 현재의 작업공간을 체크하는 메세지 박스를 표시합니다.

4. 프로그램이  파일  "korea.prt" OPEN 합니다. 아래 이미지는 "PRT0001.PRT"를 읽은 경우 입니다

 

 

5. 매개변수 이름 "EZ_PARAM4"을 생성하고, 타입은 실수 이며, 값은 38.5를 자동으로 입력 된다.

6. 만일 파일에 동일한 매개 변수 "EZ_PARAM4" 이름이 존재 하면 오류가 표시 됩니다. -예외 처리를 해야 한다.


추가>  메세지 박스에 파일이 저장된 폴더 이름 불러오기

'Show the current Working Directory
 MsgBox "This is the current Working Directory: " & vbCrLf & session.GetCurrentDirector


추가>  vbcrLf 기능 설명

 

vbCr과 vbcrLf와 chr(13) 의 차이점

캐리지리턴(CR)과 라인피드(LF)는 예전의 도트 프린터나 수동 타자기에 쓰인 부산물로 다음과 같은 동작을 합니다. Carriage Return(CR) : 현재 줄의 처음으로 커서나 헤드를 이동한다. Line Feed(LF) : 커서

blog.daum.net

추가>  korea. prt 파일 불러오기

다음과 같은 순서로 파일을 Open 합니다.  설명자 정의 -> 세션으로 불러오기 -> Creo 창에 보이기
설명자 정의는 아래와 같습니다. 여기서 "Korea.prt"  부분은 파일 이름과 확장자 입니다.


Dim oModelDescriptorCreate As New CCpfcModelDescriptor
Dim oModelDescriptor As IpfcModelDescriptor
Set oModelDescriptor = oModelDescriptorCreate.Create(EpfcMDL_PART, "KOREA.PRT", Null)

Function CCpfcModelDescriptor.Create (Type as IpfcModelType, InstanceName as String, 
                                     GenericName as String [optional]) as IpfcModelDescriptor
    
    new 모델 설명자를 만드는 함수 입니다.함수에 사용하는 매개변수는 아래와 같습니다
    
    1) Type - The model type
    2) InstanceName - The name of the model, or, if the model is an instance, the instance name.
                      This string can be neither null nor empty.
    3) GenericName  - The name of the generic model. If the model is not an instance, 
                      this attributemust be null or an empty string. (페밀리테이블)
                      
    리턴 값은 : The new ModelDescriptor

■ 입력한 폴더, 파일 이름으로 입려된 파라메터 값  보내기  코드

Option Explicit
Sub Main2()
	Dim asynconn As New pfcls.CCpfcAsyncConnection
	Dim conn As pfcls.IpfcAsyncConnection
	Dim session As pfcls.IpfcBaseSession
	Dim oModel As pfcls.IpfcModel
	Dim oWindow As pfcls.IpfcWindow
        
        '//MaKe an asynchronous connection with Creo
        Set conn = asynconn.Connect("", "", ".", 5)
        '//Get the current session
        Set session = conn.session
        '//Show the current Working Directory
        MsgBox "This is the current Working Directory: " & vbCrLf & session.GetCurrentDirectory

        '//Create a modeldescriptor to the Pro/E Model
        Dim oModelDescriptorCreate As New CCpfcModelDescriptor
        Dim oModelDescriptor As IpfcModelDescriptor
        Set oModelDescriptor = oModelDescriptorCreate.Create(EpfcMDL_PART, "KOREA.PRT", Null)

        '// Retrieve the model into the oModel handle
         Set oModel = session.RetrieveModel(oModelDescriptor)

        '// Create a new window which displays the Pro/E Model
        Set oWindow = session.OpenFile(oModelDescriptor)

        '// Activate the new window
        oWindow.Activate

        '// Show the name of the Pro/E Model in a messagebox
        MsgBox "Model name = " & oModel.Filename

        Dim solid As IpfcSolid
        Dim unitWithParam As pfcls.IpfcBaseParameter
        Dim paramOwner As pfcls.IpfcParameterOwner
        Dim ParamObject As New CMpfcModelItem
        Dim ParamValue As New CpfcParamValue
        Dim LenUnit As IpfcUnit


        Set solid = oModel
        Set LenUnit = solid.GetUnit("in", False)
        Set ParamValue = ParamObject.CreateDoubleParamValue(38.5)
        Set paramOwner = oModel
        Set unitWithParam = paramOwner.CreateParamWithUnits("EZ_Param4", ParamValue, LenUnit)
        
        oModel.Save

        'Disconnect with Pro/ENGINEER
        conn.Disconnect (2)

        'Cleanup
        Set asynconn = Nothing
        Set conn = Nothing
        Set session = Nothing
        Set oModel = Nothing

End Sub

Async_Mode_Create_Param_withUnits_Example.xlsm
0.01MB
Create_param_with_Units.txt
0.00MB

 

 

[엑셀 매크로 VBA] MsgBox 메시지 박스 창 띄우기

Excel에서 사용자에게 윈도우 창을 이용해서 정보를 출력할 수 있는 기능이 있습니다. MsgBox라는 기능인데요. MsgBox를 통해서 VBA 개발자는 정보를 메시지 창을 통해서 데이터의 현재값을 보여줄 수

guslabview.tistory.com

 

 

 


영업 문의 : lionkk@idt21c.com