我有一些VBA要删除工作簿中的所有工作表。
For Each ws In ActiveWorkbook.Worksheets
ws.Delete
Next ws
如何修改此选项以排除列表中的某些情况?伪代码看起来像:
exclude = Array("apple", "orange")
For Each ws In ActiveWorkbook.Worksheets
if ws not in array then ws.Delete
Next ws
答案 0 :(得分:3)
使用此功能测试它是否在您的数组中
Public Function InArray(arr As Variant, SearchValue As String) As Boolean
InArray = (UBound(Filter(arr, SearchValue)) > -1)
End Function
For Each ws In ActiveWorkbook.Worksheets
If Not InArray(exclude, ws.Name) Then ws.Delete
Next ws
一行更新
For Each ws In ActiveWorkbook.Worksheets
If UBound(Filter(arr, ws.Name)) = -1 Then ws.Delete
Next ws
或在上面的评论中使用@TimWilliams建议
For Each ws In ActiveWorkbook.Worksheets
If Not IsError(Application.Match(ws.Name, exclude, 0)) Then ws.Delete
Next ws