728x90

엑셀 Sheet 를 각각의 파일로 분리하여 저장하고 싶을 때 사용하는 VBA 코드이다.

시트 내보내기 코드를 접한 건 더 초보시절에 접했는데 그때는 어떻게 손을 대야 할지 몰라서 빈시트까지 내보내는 형태로 만들었다.

아래 코드는 테스트를 하면서 확인한 거라 완벽하게 동작한다.


파일시트내보내기.xlsm


Option Explicit     '//변수를 선언하지 않아 발생할 오류를 방지
Sub Save_EachSheet_Into_SeperateFiles()  '// 파일 이름 + sheet 이름으로 저장됨
'//  본 실행문은 Sheet 가 비어있는 것은 내보내기 하지 않음
    Dim wb  As Workbook
    Dim sht As Worksheet
    Dim rngUsed As Range
    Dim i%, n%
    Dim oldName, newName As String

    Application.ScreenUpdating = False
    For Each sht In Worksheets   '// 각 sheet를 순환
        If Not (sht.Cells.SpecialCells(xlCellTypeLastCell).Address(0, 0) = "A1" And sht.Cells(1, 1).Value = "") Then
            With ThisWorkbook
                oldName = Split(.Name, ".")(0)      '// 파일의 이름만 추출
                newName = .Path & "\" & oldName & "-" & sht.Name & ".xlsx" '// 현재 폴더에 새로운 파일명 지정
            End With
   
            If Dir(newName, vbDirectory) = Empty Then  '// 파일이 없으면
                Set rngUsed = sht.Cells    '// sheet의 전 영역을 복사
                Set wb = Workbooks.Add   '// 새 엑셀파일(통합문서)를 열음. 아직 파일로 저장된 것은 아님
                If ActiveWorkbook.Sheets.Count <> 1 Then   '// 새 엑셀파일 sheet 개수 1개만 남길 목적으로 검사
                    Application.DisplayAlerts = False        '// 경고창이 뜨지 않도록 설정
                        For i = ActiveWorkbook.Sheets.Count To 2 Step -1  '// 총 sheet 개수부터 시작해서 1개만 남기고 삭제
                        ActiveWorkbook.Sheets(i).Delete
                    Next i
                    Application.DisplayAlerts = True    '// 경고창이 뜨도록 되돌려 놓음
                End If
                      
                rngUsed.Copy wb.Sheets(1).[A1]
                wb.SaveAs Filename:=newName  '//파일명 저장
                wb.Close
                n = n + 1
            Else
                MsgBox newName & " 파일은 존재하므로 확인해보세요"
            End If
        End If
    Next sht

    Application.ScreenUpdating = True

    If n = 0 Then
        MsgBox "내보내기할 시트가 없습니다"
    Else
        MsgBox n & " 개 파일 생성 완료"

    End If
End Sub

* 활용하실 분은 첨부파일내에 포함된 코드를 복사해서 내보내기할 엑셀파일에 붙여넣기 해서 사용하면 됩니다.


블로그 이미지

Link2Me

,