Am writing a simple function to test of the existence of a worksheet in the current workbook
The code below evaluates to false each time even though WsName exists in the workbook wb.
Private Function WorkSheetExists(ByRef WsName As String, wb As Workbook) As Boolean
Dim i As Long
For i = 1 to i= wb.Sheets.Count
If (StrComp(WsName, wb.Sheets(i).Name) = 0) Then
WorkSheetExists = True
Exit Function
End If
Next i
WorkSheetExists = False
End Function
A little investigation reveals this is because the Exit Function statement isn't causing an exit of the Function.
My rewrite is:-
Private Function WorkSheetExists(ByRef WsName As String, wb As Workbook) As Boolean
Dim i As Long
Dim Found As Boolean
Found = False
i = 1
Do While Not Found And i <= wb.Sheets.Count
If (StrComp(WsName , wb.Sheets(i).Name) = 0) Then
Found = True
WorkSheetExists = Found
' Exit Function 'not needed as it doesn't exit function...but why?
End If
i = i + 1
Loop
WorkSheetExists = Found
End Function
The rewrite works, just wondered why the Exit Function doesn't work in scenario 1?
Bookmarks