2015-11-20 61 views
0

正在編寫一個程序來刪除所有月份名稱的工作表。但是程序後刪除片,它會給我一個自動化錯誤刪除導致自動化錯誤的工作表

Sub DelSheet() 

Dim i As Integer 
Dim months() As String 
months() = Split("January February March April May June July Auguest September October November December") 

Dim ws As Worksheet 

Application.DisplayAlerts = False 


    For Each ws In Worksheets 
     For i = 0 To UBound(months) 

      If ws.Name = months(i) Then 
       ws.Delete 
      End If 

     Next i 
    Next ws 

Application.DisplayAlerts = True 



End Sub 

難道說以後我刪除表,當它開始下一個循環中集(表)的元素已更改。

對於每個WS在工作表中

我迷路

回答

1

是 - 遍歷集合從中你可能要刪除的項目時,最好向後工作

Sub DelSheet() 

Dim i As Integer, n As Long, w as Long 
Dim months() As String 
months() = Split("January February March April May June July Auguest September October November December") 

Dim ws As Worksheet 

Application.DisplayAlerts = False 

    n = Worksheets.Count 
    For w = n to 1 Step - 1 
     Set ws = Worksheets(w) 
     For i = 0 To UBound(months) 

      If ws.Name = months(i) Then 
       ws.Delete 
       Exit For 
      End If 

     Next i 
    Next w 

Application.DisplayAlerts = True 



End Sub 
1

嗨這是另一種解決方案。在這種情況下我們只用一個循環

Sub DelSheet() 

    Const strMONTHS As String = "January February March April May June July Auguest September October November December" 

    Dim sh As Worksheet 
    Dim arrSheetsToDelete() As String 
    Dim i As Long 

    ' Loop through the sheets and create the array 
    For Each sh In ThisWorkbook.Sheets 
     If Not InStr(1, strMONTHS, sh.Name) = 0 Then 
      ReDim Preserve arrSheetsToDelete(i) 
      arrSheetsToDelete(i) = sh.Name 
      i = i + 1 
     End If 
    Next sh 

    'Delete the array of sheets 
    Application.DisplayAlerts = False 
    ThisWorkbook.Sheets(arrSheetsToDelete).Delete 
    Application.DisplayAlerts = True   

End Sub 

希望這有助於:)