What is this? With this code we can use =WorksheetExists(B3) to test any text string to see if it exists as a sheet name in the current workbook.
The ISREF function returns a Boolean (TRUE/FALSE) value in respect to its argument, whether it's a valid reference or not. Since a valid reference means that the reference exists, the function can also tell us whether a certain worksheet exists.
xls" if os. path. isfile(input_filename): print ("the document is been charged") break else: print("xls not found !") #Load the document xls_file = pd. ExcelFile(input_filename) #Select the good sheet in file print ("this is your sheets in this document",xls_file.
You could use set sh = ActiveSheet , or strShName = ActiveSheet.Name . Show activity on this post. Test for matching worksheet and workbook names.
Some folk dislike this approach because of an "inappropriate" use of error handling, but I think it's considered acceptable in VBA... An alternative approach is to loop though all the sheets until you find a match.
Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
WorksheetExists = Not sht Is Nothing
End Function
If you are specifically interested in worksheets only, you can use a simple Evaluate call:
Function WorksheetExists(sName As String) As Boolean
WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function
You don't need error handling in order to accomplish this. All you have to do is iterate over all of the Worksheets and check if the specified name exists:
Dim exists As Boolean
For i = 1 To Worksheets.Count
If Worksheets(i).Name = "MySheet" Then
exists = True
End If
Next i
If Not exists Then
Worksheets.Add.Name = "MySheet"
End If
As checking for members of a collection is a general problem, here is an abstracted version of @Tim's answer:
Function Contains(objCollection As Object, strName as String) As Boolean
Dim o as Object
On Error Resume Next
set o = objCollection(strName)
Contains = (Err.Number = 0)
Err.Clear
End Function
This function can be used with any collection like object (Shapes
, Range
, Names
, Workbooks
, etc.).
To check for the existence of a sheet, use If Contains(Sheets, "SheetName") ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With