2016-10-27 1 views
1

숫자가 아닌 이름의 시트를 삭제해야하는 서브 프로그램이 있습니다. 시트를 찾고 있지만 삭제하지는 않았습니다. 나는 이유를 알 수 없다. ...Visual Basic 및 Interop을 사용하여 Excel에서 시트 삭제

그것은 던지기 않고있다. 그리고 그것은 모든 시트와 함께 PDF를 만들고있다. 변경 내용을 저장하도록 xlsBook.Close을 설정하면 프로세스가 실행 된 후에도 통합 문서에 모든 시트가 남아 있습니다.

나는 의 MSOffice 2013비주얼 스튜디오 2015이 실행하고 있습니다. 여기에 코드 스 니펫이 있습니다.

Imports System 
    Imports System.IO 
    Imports Microsoft.Office.Interop.Excel 
    Imports Microsoft.Office.Interop.PowerPoint 
    Imports Microsoft.Office.Interop.Word 
    Imports Microsoft.Office.Core 


    Private Sub Convert_Excel(ByVal InFormat As String, ByVal InSpecial As String) 

    Dim xlsApp = New Microsoft.Office.Interop.Excel.Application() 
    Dim xlsBook As Microsoft.Office.Interop.Excel.Workbook 
    Dim xlsSheet As Microsoft.Office.Interop.Excel.Worksheet 

    xlsApp.Application.DisplayAlerts = False 

    Try 
     xlsApp.ScreenUpdating = False 
     xlsBook = xlsApp.Workbooks.Open(theFile, UpdateLinks:=False, ReadOnly:=False) 
        For Each xlsSheet In xlsBook.Sheets 
          If Not IsNumeric(xlsSheet.Name) Then 
            Try 
              xlsSheet.Delete() 
            Catch ex As Exception 
              Environment.ExitCode = ERROR_EXCEL_NOSHEETS 
            End Try 
          End If 
        Next 

     If xlsBook.Worksheets.Count > 1 And Environment.ExitCode <> ERROR_EXCEL_NOSHEETS Then 
      If LCase(InFormat) = "standard" Then 
       xlsBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, thePDFFile, XlFixedFormatQuality.xlQualityStandard, 
              True, True, Type.Missing, Type.Missing, False, Type.Missing) 
      Else 
       Environment.ExitCode = ERROR_EXCEL_BADOP 
       If Not Command_In Then 
        System.Windows.Forms.MessageBox.Show("INVALID OPERATION SELECTED") 
       End If 
      End If 
     End If 
     xlsBook.Close(SaveChanges:=False) 
     xlsApp.Quit() 
     xlsBook = Nothing 
     xlsApp = Nothing 
     pdfnameLabel.Text = "Created " & Convert_FilePDF 
    Catch ex As Exception 
     Environment.ExitCode = ERROR_EXCEL_UNKNOWN 
     If Not Command_In Then 
      System.Windows.Forms.MessageBox.Show(ex.Message) 
     End If 
    Finally 
     If xlsBook IsNot Nothing Then 
      xlsBook.Close(SaveChanges:=False) 
     End If 
     If xlsApp IsNot Nothing Then 
      xlsApp.Quit() 
     End If 
    End Try 

End Sub 
+2

마지막 시트에서 거꾸로 작업을 시도 추가 :이 컬렉션에서 항목을 삭제하는 것은 좋은 방법이 아닙니다 For Each를 사용하여 iterating하는 동안 –

+0

@TimWilliams 관련없는 메모에서 삭제할 워크 시트 목록을 만드는 것이 좋습니다 :'Dim sheetsToDelete = xlBook.Sheets.Cast Of Of Worksheet .Where (Function (x) Not Isum (x.Name)). ToList'. 그런 다음 반복 컬렉션에 대해 걱정하지 않고 해당 목록의 모든 워크 시트를 안전하게 삭제할 수 있으며 목록의 길이가 통합 문서의 모든 워크 시트 수보다 큰지 확인하는 것도 쉽습니다. –

+0

'If Not IsNumeric (xlSheet.Name) Then' 블록에서'Try..Catch'를 제거하면 어떻게됩니까? –

답변

1

@TimWilliams가 말한 것에 대해. 왜 여기에 오류가 발생하는지 확신 할 수 없습니다.

For Each xlsSheet In xlsBook.Sheets 
    If Not IsNumeric(xlsSheet.Name) Then 
     Try 
      xlsSheet.Delete() ' <-- should error here 
     . . . . . . . . 

변이 집합에 대해서는 While 루프를 사용해야합니다.

Dim index as Integer 
While index < xlsBook.Sheets.Count -1 
    . . . . . . . 
    ' here, when you remove Sheets(index), don't increment it 
    ' because next sheet will now have this index. 
    ' NOTE, I am not sure if sheets it 0 or 1-based collection    

실제로 for 루프를 while 루프로 변경하기 전까지는 정확히 어디에서 문제가 발생하는지 명확하지 않습니다.

업데이트 일부 돌아가서 앞으로 당신이 [삭제하기 전에]해야한다는 것 후

xlsApp.Application.DisplayAlerts = False 
+0

통합 문서를 저장하려고하지 않습니다. 그냥 시트를 삭제하고 PDF로 내보낼 수 있습니다. 나는 지표를 사용하지 않는다. 나는 xlsSheet가 삭제 될 삭제 메서드가있는 실제 워크 시트 였기 때문에 생각했습니다. – wrkoch

+0

@ wrkoch Ok. 벌금. 그것은 삭제 하겠지만'xlsBook.Sheets' 콜렉션은 돌연변환되어'for-loop'에 대해 생성 된 열거자는 더 이상 유효하지 않습니다 –

+0

어디로 가는지 알고 있습니다. 나는 그것을 줄 것이다. – wrkoch