컴퓨터/엑셀

엑셀vba 시트 지우기

풍경소리^^ 2024. 3. 1. 06:42
Sub DeleteSheetsExceptRequired()
    Dim ws As Worksheet
    Dim keepSheetNames() As String
    Dim sheetExists As Boolean
    Dim i As Integer
    
    ' 남겨야 하는 시트의 이름을 배열에 저장합니다.
    keepSheetNames = Array("총계정원장", "양식")
    
    Application.DisplayAlerts = False ' 시트 삭제 경고를 무시합니다.
    
    ' 각 시트를 순환하면서 남겨야 하는 시트인지 확인하고, 아닌 시트는 삭제합니다.
    For Each ws In ThisWorkbook.Sheets
        sheetExists = False
        For i = LBound(keepSheetNames) To UBound(keepSheetNames)
            If ws.Name = keepSheetNames(i) Then
                sheetExists = True
                Exit For
            End If
        Next i
        
        If Not sheetExists Then
            ws.Delete
        End If
    Next ws
    
    Application.DisplayAlerts = True ' 시트 삭제 경고를 다시 활성화합니다.
End Sub