Thread: Find worksheet
View Single Post
  #6   Report Post  
Posted to microsoft.public.excel.programming
Jim Thomlinson[_3_] Jim Thomlinson[_3_] is offline
external usenet poster
 
Posts: 983
Default Find worksheet

I set the blnReturnValue = False (not necessary as it would be initialized
that way but it makes the code a little more readable). I then only switch
the variable to true if I get a match at any point. It does not rely on the
last sheet, only the last value it was set too. I have a bias in functions
that I always set the returned value as the last line of code in the
function. It makes debugging a little easier in my opinion if you only set
the returned value once at the very end... My prof for C was adamant on the
point and I have never lost that style...

"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!