2012-08-15 2 views
1

메인 프레임에서 가져온 데이터로 계속 작업하고 있습니다. 데이터는 주로 alphanumeric이며, 계속해서 building functionality onto past efforts입니다. 시트가 이동되는 루프는이 SO article에서 논의 된 기능에 기초하여 생성되었습니다.새로 만든 워크 시트 및 버전 변경된 워크 시트 VBA

나는 SO article과상의했으나 이러한 기능의 일반적인 형식을 독립적으로 테스트했지만이 문제는 버전 문제 나 새 통합 문서를 참조하는 방식으로 인해 발생합니다.

한 통합 문서의 워크 시트를 다른 통합 문서로 옮기는 서브 루틴을 작성했습니다. 이는 체크 박스에 연결된 공용 변수와 함께 사용되며 양식 데이터를 쉽게 포팅 할 수있는 방법을 사용자에게 제공하기위한 것입니다. 공용 변수는 체크 표시가 선택 상태 인 경우 조건부에서 서브 루틴을 호출하는 데 사용됩니다. 다음과 같이

코드는 다음과 같습니다

Public Sub MoveSheets() 

' This macro moves all sheets but those noted within the If statements,(1) 
' (1) which are further nested within the For Each loop. 

'See http://msdn.microsoft.com/en-us/library/office/ff198017.aspx for save file format types. 
'The file format of this excel macro sheet is 52: xlOpenXMLWorkbookMacroEnabled 
'The default save type for the use-case is excel 2003 is compatibility mode. 
'The macro is to set the current save type to one compatible with 52. 
'In this case, 51: xlOpenXMLWorkbook was selected as the selected type. 

'Define Excel Format storage variables. 
Dim FileFormatSet As Excel.XlFileFormat 
Dim OriginalFileFormatSet As Excel.XlFileFormat 
Dim TempFileFormatSet As Excel.XlFileFormat 


'Define worksheet/workbook variables. 
Dim IndividualWorkSheet As Worksheet 
Dim NewWorkBook1 As Workbook 

'Set variable to store current time. 
Dim CurrentTime As Date 

'The original file format. 
OriginalFileFormatSet = Application.DefaultSaveFormat 

'The file format to be used at the end of the procedure after all is said and done. 
FileFormatSet = OriginalFileFormatSet 

'The currently desired file format. 
TempFileFormatSet = xlOpenXMLWorkbook 

'The currently desired file format set as the set default. 
Application.DefaultSaveFormat = TempFileFormatSet 

'Disable application alerts. Comment the line below to display alerts (2) 
'(2) in order to help check for errors. 
Application.DisplayAlerts = False 

'Save new workbook "NewWorkBook" as default file format. 
Workbooks.Add.SaveAs Filename:="NewWorkBook", FileFormat:=Application.DefaultSaveFormat 

'Set variable to new workbook "NewWorkBook", which is in .xlsx format. 
Set NewWorkBook1 = Workbooks("NewWorkBook.xlsx") 

'Activate Macro Window. 
Windows("ShifterMacro.xlsm").Activate 
'For each worksheet, shift it to the workbook "NewWorkBook" if (3) 
'(3) it fails outside the criteria set listed below. 
For Each IndividualWorkSheet In ThisWorkbook.Worksheets 
    If IndividualWorkSheet.Name <> "Sheet1" And IndividualWorkSheet.Name <> "Criteria" And _ 
    IndividualWorkSheet.Name <> "TemplateSheet" And IndividualWorkSheet.Name <> "TemplateSheet2" And _ 
    IndividualWorkSheet.Name <> "Instructions" And IndividualWorkSheet.Name <> "Macro1" And _ 
    IndividualWorkSheet.Name <> "DataSheet" Then 

      'Select each worksheet. 
      IndividualWorkSheet.Select 

      'Shift the worksheetover to the new workbook. 
      '****NOTE: THIS CODE CURRENTLY RESULTS IN A '1004' RUN-TIME ERROR.**** 
      IndividualWorkSheet.Move After:=NewWorkBook1.Sheets.Count 

    End If 
Next 

'An ugly set of If Then statements to clean the new workbook (4) 
'(4) of its previous sheets, assuming entries are to be made. 
If NewWorkBook1.Sheets.Count > 1 Then 

    NewWorkBook1.Sheets("Sheet1").Delete 

End If 

If NewWorkBook1.Sheets.Count > 1 Then 

    NewWorkBook1.Sheets("Sheet2").Delete 

End If 

If NewWorkBook1.Sheets.Count > 1 Then 

    NewWorkBook1.Sheets("Sheet3").Delete 

End If 

'********** CODE CHECKED BUT UNTESTED WITHIN THESE BOUNDARIES ********** 

'Activate the Window for the new workbook if it is inactive. 
Windows("NewWorkBook.xlsx").Activate 

'If the number of sheets are greater than 1... (5) 
If Sheets.Count > 1 Then 

    '(6) The time value is parsed to remove unusual characters, following (5) 
    '(6) the logic of this SO article: https://stackoverflow.com/questions/11364007/save-as-failed-excel-vba. 

    'Formatted current time as per http://www.mrexcel.com/forum/excel-questions/273280-visual-basic-applications-format-now-yyyymmddhhnnss.html 
    CurrentTime = Format(Now(), "yyyy-mm-dd-hh-nn-ss") 

    '(5) Then go ahead and save the file with the current date/time information. 
    NewWorkBook1.SaveAs Filename:="Form_Data_" & Now, FileFormat:=Application.DefaultSaveFormat 

End If 

'Set SaveChanges = True, as per https://stackoverflow.com/questions/9327613/excel-vba-copy-method-of-worksheet-fails 
ActiveWorkbook.Close SaveChanges:=True 

'********** END CODE BOUNDARY ********** 

'Activate the Window for the Macro. 
Windows("ShifterMacro.xlsm").Activate 

'Activate a specific sheet of the Macro. 
ActiveWorkbook.Sheets("Instructions").Activate 

'Change Display Alerts back to normal. 
Application.DisplayAlerts = True 

'Reset the view for the original data sheet. 
With Sheets("Sheet1") 

'For when this process is repeated. 
If .FilterMode Then .ShowAllData 

End With 

'Return the Default save format to the original file format. 
Application.DefaultSaveFormat = FileFormatSet 

End Sub 

코드 라인 (62)에 실패하고, '1004'런타임 오류의 결과 :

IndividualWorkSheet.Move After:=NewWorkBook1.Sheets.Count 

참조하는 워크 시트가 올바른 테스트를 보유하고 값은 '100-AAA'입니다. Sheets.Count는 3입니다. NewWorkBook1 변수의 값은 NewWorkBook.xslx입니다. 생성 된 통합 문서 "NewWorkBook.xslx"의 경로는 매크로 통합 문서와 동일합니다. 2007 년의 용량과 설치 용량을 가지고 있지만 사용자의 기본 설정은 2003이지만 2007 년에 Excel 버전이 출시되었습니다.

왜이 런타임 오류가 발생하여 Move이 발생하며이를 수정하는 이유는 무엇입니까? 새로 생성 된 통합 문서로 내 워크 시트를 가져 오려면 오류가 발생 했습니까?

답변

4

이 :

IndividualWorkSheet.Move After:=NewWorkBook1.Sheets.Count

단지 (NewWorkBook1 부모 통합 문서보다 더 많은 시트가있는 경우 그것은 오류가 발생하지)

어쩌면 시도 같은 통합 문서 내에서 시트를 이동하는 지정

IndividualWorkSheet.Move After:=NewWorkBook1.Sheets(NewWorkBook1.Sheets.Count)

+0

Tim, 수정 프로그램은 매우 잘 작동합니다. 고마워, 나는 완전히 분명한 해결책을 놓쳤다. – JackOrangeLantern

+0

+1 멋지게 완료되었습니다. :) –

관련 문제