Delete Excel worksheets if not in array
The code below is used to delete worksheets that are not in the array. While the below code can run successfully, there is a problem from my understanding.
As there is a boolean "Matched" declared as False as default (root level), so if wsName = ws.Name, then it will be assigned Matched = True (parent level). So, for those that not wsName = ws.Name, they should be False right?
When those that are not matched and exit for the loop, and run the next line, they are supposed to be False and matched the parent False, but I don't understand why the next line said "If not Matched.." Quite contradict my logical thinking.
I am new to VBA so hope anyone can help me.
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
If Not Matched Thenis doing:If Not Matched Thenis the same asIf Matched <> True Then- it's checking the value of Matched to see if it is False or True. - Jerry Jeremiah