如果不在数组中,则删除Excel工作表

时间:2016-08-27 18:20:19

标签: excel vba excel-vba

我有解决错误的问题"时间执行错误#13:不兼容的类型"。如果用户创建了一些未在数组中声明的工作表,则会将其删除。有人可以帮忙吗?

a

3 个答案:

答案 0 :(得分:6)

您的代码行说:

Set wsP = ThisWorkbook.Worksheets(ArrayOne)

正在尝试将Worksheet对象设置为许多工作表的数组。这就像尝试将单个整数设置为整​​数数组一样。

尝试使用以下代码

Sub DeleteNewSheets()

    Dim ws As Worksheet
    Dim ArrayOne() As Variant
    Dim wsName As Variant
    Dim Matched As Boolean

    ArrayOne = Array("SheetA", "SheetB", "SheetC", "Sheet_n")

    Application.DisplayAlerts = False

    For Each ws In ThisWorkbook.Worksheets
        Matched = False
        For Each wsName In ArrayOne
            If wsName = ws.Name Then
                Matched = True
                Exit For
            End If
        Next
        If Not Matched Then
            ws.Delete
        End If
    Next ws

    Application.DisplayAlerts = True

End Sub

答案 1 :(得分:1)

如果你添加一个额外的 For ... Next For Each ... Next 语句来遍历ArrayOne中的每个元素并且条件 IF s声明然后它应该做的工作。所以你的代码应该是这样的

    Sub DeleteNewSheets()

    Dim ws As Worksheet
    Dim ArrayOne As Variant, iSheet As Integer

    Application.DisplayAlerts = False

    ArrayOne = Array("SheetA", "SheetB", "SheetC", "Sheet_n")

    For Each ws In ThisWorkbook.Worksheets
        For iSheet = LBound(ArrayOne) To UBound(ArrayOne)
            If ws.Name = ArrayOne(iSheet) Then Exit For
            If iSheet = UBound(ArrayOne) Then
                ws.Delete
            End If
        Next
    Next

    Application.DisplayAlerts = True

End Sub

或者

Sub DeleteNewSheets()

Dim ws As Worksheet
Dim ArrayOne As Variant

    Application.DisplayAlerts = False

    ArrayOne = Array("SheetA", "SheetB", "SheetC", "Sheet_n")

    For Each ws In ThisWorkbook.Worksheets
        For Each Element In ArrayOne
            If ws.Name = Element Then Exit For
            If Element = ArrayOne(UBound(ArrayOne)) Then
                ws.Delete
            End If
        Next
    Next

    Application.DisplayAlerts = True

End Sub

答案 2 :(得分:0)

你可以在一个循环中查看工作表并删除" bad"一次拍摄如下:

Option Explicit

Sub DeleteNewSheets()
    Dim ws As Worksheet
    Dim sheetsToDelete As String
    Const GOODSHEETS As String = "\SheetA\SheetB\SheetC\Sheet_n\" '<--| list of good sheets names, separated by an invalid character for sheet names 

    For Each ws In ThisWorkbook.Worksheets
        If InStr(GOODSHEETS, "\" & ws.Name & "\") = 0 Then sheetsToDelete = sheetsToDelete & ws.Name & "\" '<--| update sheets to be deleted list
    Next ws

    If sheetsToDelete <> "" Then '<--| if the list is not empty
        sheetsToDelete = Left(sheetsToDelete, Len(sheetsToDelete) - 1) '<--| remove last delimiter ("\") from it
        Application.DisplayAlerts = False
        ThisWorkbook.Worksheets(Split(sheetsToDelete, "\")).Delete '<-- delete sheets
        Application.DisplayAlerts = True
    End If
End Sub