source

Excel vba 시트 모듈에 프로그래밍 방식으로 코드 추가

ittop 2023. 7. 1. 09:58
반응형

Excel vba 시트 모듈에 프로그래밍 방식으로 코드 추가

프로그래밍 방식으로 생성된 워크북에 아래와 유사한 이벤트 코드를 넣는 방법:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim nextTarget As Range

    Set nextTarget = Range(Selection.Address) 'store the next range the user selects

    Target.Columns.Select 'autofit requires columns to be selected
    Target.Columns.AutoFit

    nextTarget.Select
End Sub

이를 통해 워크북을 추가하고 워크시트 변경 이벤트를 시트 1 모듈에 배치합니다.

Sub AddSht_AddCode()
    Dim wb As Workbook
    Dim xPro As VBIDE.VBProject
    Dim xCom As VBIDE.VBComponent
    Dim xMod As VBIDE.CodeModule
    Dim xLine As Long

    Set wb = Workbooks.Add

    With wb
        Set xPro = .VBProject
        Set xCom = xPro.VBComponents("Sheet1")
        Set xMod = xCom.CodeModule

        With xMod
            xLine = .CreateEventProc("Change", "Worksheet")
            xLine = xLine + 1
            .InsertLines xLine, "  Cells.Columns.AutoFit"
        End With
    End With

End Sub

코드를 처음 실행할 때 오류가 발생할 수 있습니다.

enter image description here

Stop(중지) 아이콘을 누르고 도구 메뉴와 "References(참조)"를 선택합니다.

enter image description here

enter image description here

그런 다음 "Microsoft Visual Basic for Applications Extensibility 5.3 라이브러리"를 찾아 확인합니다.

enter image description here

코드를 다시 실행하면 작동합니다.

언급URL : https://stackoverflow.com/questions/34837006/excel-vba-add-code-to-sheet-module-programmatically

반응형