Predefinição:Taxonomia/Vachellia
Saltar para a navegação
Saltar para a pesquisa
import win32com.client as win32 import os
def add_vba_macro_to_excel(file_path):
excel = win32.DispatchEx("Excel.Application")
excel.Visible = False # 엑셀 창 숨김
# 엑셀 파일 열기 workbook = excel.Workbooks.Open(file_path) # VBA 매크로 코드 vba_code = """
Private Sub Worksheet_Change(ByVal Target As Range)
' 변경된 범위가 B열에 있는지 확인
If Not Intersect(Target, Me.Columns("B")) Is Nothing Then
' 첫 번째 행은 제목 행이므로 건너뛰기
Call AutoNumberWithMergedCells
End If
End Sub
Sub AutoNumberWithMergedCells()
Dim ws As Worksheet Dim rng As Range Dim cell As Range Dim currentNumber As Long
' 현재 활성 시트 가져오기
Set ws = ThisWorkbook.ActiveSheet
' 데이터가 있는 마지막 행 찾기 (B열 기준)
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
' 초기 순번 설정
currentNumber = 1
' A열의 순번 초기화 (제목 행을 제외하고)
ws.Range("A2:A" & lastRow).ClearContents
' 순번 입력 (제목 행을 제외하고)
For Each cell In ws.Range("A2:A" & lastRow)
' 해당 셀의 병합 범위 가져오기
Set rng = cell.MergeArea
' 병합된 셀의 첫 번째 셀에만 순번 부여
If cell.Address = rng.Cells(1, 1).Address Then
cell.Value = currentNumber
currentNumber = currentNumber + 1
End If
Next cell
End Sub
""" # VBA 모듈 추가 vb_module = workbook.VBProject.VBComponents.Add(1) # 1은 vbext_ct_StdModule (표준 모듈) vb_module.Name = "AutoNumberModule" vb_module.CodeModule.AddFromString(vba_code) # 엑셀 파일 저장 workbook.SaveAs(file_path, FileFormat=52) # xlsm 포맷으로 저장 workbook.Close(SaveChanges=True) excel.Quit()
- 파일 경로 설정
script_path = os.path.dirname(__file__) file_path = os.path.join(script_path, "YourWorkbook.xlsm")
- VBA 매크로 추가
add_vba_macro_to_excel(file_path)