不要删除工作表,如果它在数组中

Dim L As Double Dim Workings() As Variant Workings = Array("Due SO not Billed", "Working Paper", "Ageing Over 14 Days") On Error Resume Next Application.DisplayAlerts = False For L = 1 To Worksheets.Count If Worksheets(L).Name <> Workings Then Worksheets(L).Delete Exit For End If Next L Application.DisplayAlerts = True On Error GoTo 0 

我试着写上面的代码。 目的是我有一个工作簿10工作表,但最终的输出只需要3张,我想删除其余的工作表。 我尝试了上面的代码与数组,无论我给在数组中的任何名称应保存,所有其他剩余的表应该被删除。 我收到types不匹配错误。 有人可以帮忙吗?

使用“ Match来testing工作表的Name是否在数组中:

 Dim Workings() As Variant Dim ws As Worksheet Workings = Array("Due SO not Billed", "Working Paper", "Ageing Over 14 Days") Application.DisplayAlerts = False For Each ws In Worksheets If IsError(Application.Match(ws.Name, Workings, False)) Then ws.Delete End If Next Application.DisplayAlerts = True 

闻起来像功课。 它不工作,因为工作variables是一个数组,而另一个是一个string,他们是不同的types。 testing一个string是否在数组中

  If Not IsInArray(Worksheets(L).Name, Workings) Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1) End Function 

使用VBAfilterfunction为您提供了比较文本的额外好处。 这样你就不必关心大写。

 Sub DeleteWorksheets() Dim Workings() As Variant Dim ws As Worksheet Workings = Array("Due SO not Billed", "Working Paper", "Ageing Over 14 Days") Application.DisplayAlerts = False For Each ws In Worksheets If UBound(Filter(Workings, ws.Name, True, vbTextCompare)) = -1 Then ws.Delete Next Application.DisplayAlerts = True End Sub 

这是我的valueInArray函数:

 Public Function valueInArray(myValue As Variant, myArray As Variant) As Boolean Dim cnt As Long For cnt = LBound(myArray) To UBound(myArray) If CStr(myValue) = CStr(myArray(cnt)) Then valueInArray = True Exit Function End If Next cnt End Function 

这是相当多的代码,它循环,但它的作品。 另外,对于整数和string都可以。