使用字符串的VBA Excel宏删除表

时间:2014-07-17 08:26:35

标签: excel vba excel-vba

我使用了一些VBA代码来搜索某个字符串中工作簿中的所有工作表名称,我们称之为“Text”。当它找到带有该字符串的工作表时,它应该删除该工作表。但是,我们可以说名称中有四个“Text”表单(名为文本1 文本2 文本3 text 4 ),而不是删除所有四个,它删除文字1 文字3 。它将第2和第4个保留为未删除。然后,如果我再次调用宏,则删除文本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

3 个答案:

答案 0 :(得分:13)

您需要向后循环以避免跳过工作表:

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永远不会被处理。

答案 1 :(得分:3)

我不是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

答案 2 :(得分:2)

您还可以减少n而不是在删除工作表时增加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