如果工作表位于数组

时间:2017-12-11 03:40:55

标签: excel vba excel-vba

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张,我想删除其余的工作表。我尝试使用数组上面的代码,我应该保存我在数组中给出的任何名称,并删除所有其他剩余的表。我遇到类型不匹配错误。有人可以帮忙吗?

4 个答案:

答案 0 :(得分:3)

使用Match来测试工作表的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

答案 1 :(得分:2)

闻起来像家庭作业。它不起作用,因为Workings变量是一个数组而另一个是字符串,它们是不同的类型。要测试字符串是否在数组内,请执行

 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

答案 2 :(得分:0)

使用VBA过滤器功能为您提供比较文本的额外好处。通过这种方式,您不必担心大写。

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

答案 3 :(得分:0)

这是我的@RequestMapping(path = "{username}", method = RequestMethod.GET) public Map readAllData(@PathVariable String username) { Map<String, Object> items = new HashMap(); items.put("dailyData", allData.readDailyData(username)); items.put("monthlyData", allData.readMonthlyData(username)); return items; } 功能:

valueInArray

这是很多代码,它循环,但它的工作原理。另外,它对整数和字符串都有效。