The strcomp is a very good point. You are absolutely correct. I personally
never refer to sheet names in code since the user can change those... Darn
users... As for the exit for, it is not really crucial. Nice perhaps but how
many sheet will we be dealing with. The code will look through all of the
sheets so fast that it really will not matter to any significant degree...
The code will complete long before the screen has had the chance to refresh...
As for your second option I always avoid generating errors when I can
reasonably do so. Errors have way too much overhead and it is a bias of mine
errors should only be generated because something went horribly wrong and now
I need to react gracefully...
Thanks for the input...
"keepITcool" wrote:
Jim..
I think you forgot a crucial exit for :)
as is it will only give a true if the search sheet is the last one..
also your search is case sensitive.. which may be unexpected
edited:
Function SheetExists(ByVal SheetName As String) As Boolean
Dim wks As Worksheet
For Each wks In Worksheets
If StrComp(wks.Name, SheetName, vbTextCompare) = 0 Then
SheetExists = True
Exit For
End If
Next wks
End Function
or alternative
Function WorkSheetExists(SheetName$, Optional wkb As Workbook) As
Boolean
On Error GoTo TheExit
If wkb Is Nothing Then Set wkb = ActiveWorkbook
WorkSheetExists = Not wkb.Worksheets(SheetName) Is Nothing
TheExit:
End Function
--
keepITcool
| www.XLsupport.com | keepITcool chello nl | amsterdam
Jim Thomlinson wrote :
Try this
Sub test()
MsgBox "Sheet1 Esists? " & SheetExists("Sheet1")
MsgBox "asdf Esists? " & SheetExists("asdf")
End Sub
Public Function SheetExists(ByVal SheetName As String) As Boolean
Dim wks As Worksheet
For Each wks In Worksheets
If strComp(wks.Name,SheetName,vbCompareText) = 0 Then
sheetexists = True
exit for
end if
Next wks
End Function
HTH
"cottage6" wrote:
I'm working with some code that opens a file and then needs to
determine if a specific worksheet exists in that file. How can I
determine that? Thanks as always!