VBA Excelmacros删除带有string的表格

我已经使用了一些VBA代码来search某个string的工作簿中的所有工作表名称,我们称之为“文本” 。 当它find带有该string的工作表时,应该删除该工作表。 但是假设名称中有“文本” (名为文本1文本2文本3文本4 )的四张表格,而不是全部删除,则删除文本1文本3 。 它留下第二和第四作为非删除。 然后,如果我再次调用macros,它会删除文本2,但会留下文本4 。 最后,如果我再次点击它删除文本4.我不能解决它为什么看起来应该工作。

Dim i As Integer, n As Integer n = ThisWorkbook.Worksheets.Count i = 1 Application.DisplayAlerts = False Application.ScreenUpdating = False Do On Error Resume Next If InStr(1, Sheets(i).Name, "Text") Then Sheets(i).Delete On Error GoTo 0 i = i + 1 Loop Until i = n Application.DisplayAlerts = True Application.ScreenUpdating = True 

您需要向后循环以避免跳页:

 Dim i As Integer, n As Integer n = ThisWorkbook.Worksheets.Count Application.DisplayAlerts = False Application.ScreenUpdating = False For i = n to 1 step -1 On Error Resume Next If InStr(1, Sheets(i).Name, "Text") Then Sheets(i).Delete On Error GoTo 0 Next i Application.DisplayAlerts = True Application.ScreenUpdating = True 

否则,如果代码删除纸张1,纸张2变成纸张1,但i增加到2,因此原始纸张2从不处理。

我不是VBA的职业选手,但是如果你想投篮的话,这可能也会起作用;)

 Dim WS As Worksheet Application.DisplayAlerts = False Application.ScreenUpdating = False For Each WS In Worksheets ' Specify the "TEXT" you are looking for in the sheet name in uppercase! If InStr(UCase(WS.Name), "TEXT") Then WS.Delete On Error GoTo 0 Next WS Application.DisplayAlerts = True Application.ScreenUpdating = True 

您也可以减lessn,而不会增加i,因为工作表被删除:

 Dim i As Integer, n As Integer n = ThisWorkbook.Worksheets.Count i = 1 Application.DisplayAlerts = False Application.ScreenUpdating = False Do On Error Resume Next If InStr(1, Sheets(i).Name, "Text") Then Sheets(i).Delete n = n-1 Else On Error GoTo 0 i = i + 1 End If Loop Until i = n Application.DisplayAlerts = True Application.ScreenUpdating = True