2010-07-26 2 views
2

ShowPages() 명령을 피벗 테이블에서 실행하고 각 시트를 별도의 파일로 저장하는 기능이 있습니다. 여기Excel 2003 VBA : 변수가 참조하는 새 통합 문서로 시트 이동

내가 그것을 할 수하고자하는 방법은 다음과 같습니다

Sub Split() 
    ThisWorkbook.Sheets("Data").PivotTables("Data").ShowPages PageField:="Codename" 
    Dim newWb As Workbook 

    For Each s In ThisWorkbook.Sheets 
     If s.Name <> "Data" Then 
      Set newWb = s.Move #This is the line I'm trying to work out 
      newWb.SaveAs Filename:="C:\Export\" + s.Name + ".xls" 
      newWb.Close 
     End If 
    Next s 

End Sub 

를 불행하게도,이 생성 된 객체와 그와 같은을 (당연하게도) 가지고 있지 함께 할 문제의 무리로 실행됩니다. 이 작업을 수행하는 가장 합리적인 방법은 무엇입니까?

답변

6
Sub Split() 
ThisWorkbook.Sheets("Data").PivotTables("Data").ShowPages PageField:="Codename" 
Dim newWb As Workbook 

For Each s In ThisWorkbook.Sheets 
    If s.Name <> "Data" Then 
     ''Added by Soldieraman 
     Dim sheetName As String 
     sheetName = s.Name 

     Set newWb = Workbooks.Add 
     s.Move before:=newWb.Sheets(1) 
     Application.DisplayAlerts = False 
     newWb.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Delete 
     Application.DisplayAlerts = True 

     ''Edited by soldieraman 
     newWb.SaveAs Filename:="C:\Export\Test" & sheetName & ".xls" 
     newWb.Close 
    End If 
Next s 
End Sub 
2

이것은 오래되었지만 soldieraman의 대답은 매우 좋지만 한 가지를 추가하고 싶었습니다. Excel VBA Sheets.Copy 및 Sheets.Move 메서드에는 매우 유용한 기능이 있습니다. "Before"또는 "After"의 두 가지 선택적 인수 중 하나를 사용하여 이동/복사 된 시트의 위치를 ​​지정합니다.

If you don't specify either Before or After, Microsoft Excel 
creates a new workbook that contains the moved [copied] sheet. 

그래서, 거의 놀라운 일이다,하지만 당신은 말을 바로 할 수 있습니다 : 엑셀 문서가 있다고 지적 허용 대답에

Sheets(sheetname).Move 

, 대신 :

Set newWb = Workbooks.Add 
s.Move before:=newWb.Sheets(1) 
Application.DisplayAlerts = False 
newWb.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Delete 
Application.DisplayAlerts = True 

나머지 병사의 코드는이 단순화로 잘 작동합니다.