VBA sub doesn't select the range of a specific Worksheet - excel

I just want to get the range from A1:A80 from a sheet called "Children" but I debug it, it gets nothing. Here's my code below:
Dim wks2 As Worksheet
Dim children As Range
Worksheets("Children").Activate
Set wks2 = Worksheets("Children")
Set children = wks2.Range("A1:A80")
ResetChild (children) //The sub that I want to call. Explanation bellow.
In the function ResetChild I want to delete all the sheets in my Workbook, that have names equal to the first column of the sheet Children. (A1:A80) So here's my sub below:
Sub ResetChild(children As Range)
Call DisableCalculations
Dim cell As Range
For Each cell In children
Set childrenSheet = Worksheets(cell.Value)
If (DoesSheetExist(childrenSheet)) Then
Application.DisplayAlerts = False
Sheets(childrenSheet).Delete
Application.DisplayAlerts = True
End If
End Sub

Your code should work.
How do you know that it returns nothhing?
put the row in the end of your code
Debug.Print children.Count
if it returns >0 then all ok and children is the range object with data

Maybe try something like this:
Sub DeleteChildren()
Dim children As Range
Dim oChildSheet As Worksheet
Dim vChildName
Set children = ThisWorkbook.Worksheets("Children").Range("A1:A80")
For Each vChildName In children
Set oChildSheet = GetChildSheet(CStr(vChildName))
If Not oChildSheet Is Nothing Then
Application.DisplayAlerts = False
Call oChildSheet.Delete
Application.DisplayAlerts = True
End If
Next vChildName
End Sub
Function GetChildSheet(sChildName As String) As Worksheet
On Error GoTo errHandler
Set GetChildSheet = ThisWorkbook.Worksheets(sChildName)
Exit Function
errHandler:
Debug.Print "Child sheet not found: " & sChildName
End Function

Related

Checking sheet existance using vba code and then run my macro within sheet [duplicate]

Dim wkbkdestination As Workbook
Dim destsheet As Worksheet
For Each ThisWorkSheet In wkbkorigin.Worksheets
'this throws subscript out of range if there is not a sheet in the destination
'workbook that has the same name as the current sheet in the origin workbook.
Set destsheet = wkbkdestination.Worksheets(ThisWorkSheet.Name)
Next
Basically I loop through all sheets in the origin workbook then set destsheet in the destination workbook to the sheet with the same name as the currently iterated one in the origin workbook.
How can I test if that sheet exists? Something like:
If wkbkdestination.Worksheets(ThisWorkSheet.Name) Then
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") ...
I wrote this one:
Function sheetExist(sSheet As String) As Boolean
On Error Resume Next
sheetExist = (ActiveWorkbook.Sheets(sSheet).Index > 0)
End Function
Corrected:
Without error-handling:
Function CheckIfSheetExists(SheetName As String) As Boolean
CheckIfSheetExists = False
For Each WS In Worksheets
If SheetName = WS.name Then
CheckIfSheetExists = True
Exit Function
End If
Next WS
End Function
In case anyone wants to avoid VBA and test if a worksheet exists purely within a cell formula, it is possible using the ISREF and INDIRECT functions:
=ISREF(INDIRECT("SheetName!A1"))
This will return TRUE if the workbook contains a sheet called SheetName and FALSE otherwise.
Compact wsExists function (without reliance on Error Handling!)
Here's a short & simple function that doesn't rely on error handling to determine whether a worksheet exists (and is properly declared to work in any situation!)
Function wsExists(wsName As String) As Boolean
Dim ws: For Each ws In Sheets
wsExists = (wsName = ws.Name): If wsExists Then Exit Function
Next ws
End Function
Example Usage:
The following example adds a new worksheet named myNewSheet, if it doesn't already exist:
If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"
More Information:
MSDN : For Each…Next Statement (VBA)
MSDN : Exit Statement (VBA)
MSDN : Comparison Operators (VBA)
My solution looks much like Tims but also works in case of non-worksheet sheets - charts
Public Function SheetExists(strSheetName As String, Optional wbWorkbook As Workbook) As Boolean
If wbWorkbook Is Nothing Then Set wbWorkbook = ActiveWorkbook 'or ThisWorkbook - whichever appropriate
Dim obj As Object
On Error GoTo HandleError
Set obj = wbWorkbook.Sheets(strSheetName)
SheetExists = True
Exit Function
HandleError:
SheetExists = False
End Function
.
Many years late, but I just needed to do this and didn't like any of the solutions posted... So I made one up, all thanks to the magic of (SpongeBob rainbow hands gesture) "Evaluate()"!
Evaluate("IsError(" & vSheetName & "!1:1)")
Returns TRUE if Sheet does NOT exist; FALSE if sheet DOES exist.
You can substitute whatever range you like for "1:1", but I advise against using a single cell, cuz if it contains an error (eg, #N/A), it will return True.
Short and clean:
Function IsSheet(n$) As Boolean
IsSheet = Not IsError(Evaluate("'" & n & "'!a1"))
End Function
Put the test in a function and you will be able to reuse it and you have better code readability.
Do NOT use the "On Error Resume Next" since it may conflict with other part of your code.
Sub DoesTheSheetExists()
If SheetExist("SheetName") Then
Debug.Print "The Sheet Exists"
Else
Debug.Print "The Sheet Does NOT Exists"
End If
End Sub
Function SheetExist(strSheetName As String) As Boolean
Dim i As Integer
For i = 1 To Worksheets.Count
If Worksheets(i).Name = strSheetName Then
SheetExist = True
Exit Function
End If
Next i
End Function
Public Function WorkSheetExists(ByVal strName As String) As Boolean
On Error Resume Next
WorkSheetExists = Not Worksheets(strName) Is Nothing
End Function
sub test_sheet()
If Not WorkSheetExists("SheetName") Then
MsgBox "Not available"
Else MsgBox "Available"
End If
End Sub
Why not just use a small loop to determine whether the named worksheet exists? Say if you were looking for a Worksheet named "Sheet1" in the currently opened workbook.
Dim wb as Workbook
Dim ws as Worksheet
Set wb = ActiveWorkbook
For Each ws in wb.Worksheets
if ws.Name = "Sheet1" then
'Do something here
End if
Next
For Each Sheet In Worksheets
If UCase(Sheet.Name) = "TEMP" Then
'Your Code when the match is True
Application.DisplayAlerts = False
Sheet.Delete
Application.DisplayAlerts = True
'-----------------------------------
End If
Next Sheet
If you are a fan of WorksheetFunction. or you work from a non-English country with a non-English Excel this is a good solution, that works:
WorksheetFunction.IsErr(Evaluate("'" & wsName & "'!A1"))
Or in a function like this:
Function WorksheetExists(sName As String) As Boolean
WorksheetExists = Not WorksheetFunction.IsErr(Evaluate("'" & sName & "'!A1"))
End Function
Change "Data" to whatever sheet name you're testing for...
On Error Resume Next
Set DataSheet = Sheets("Data")
If DataSheet Is Nothing Then
Sheets.Add(after:=ActiveSheet).Name = "Data"
''or whatever alternate code you want to execute''
End If
On Error GoTo 0
Without any doubt that the above function can work, I just ended up with the following code which works pretty well:
Sub Sheet_exist ()
On Error Resume Next
If Sheets("" & Range("Sheet_Name") & "") Is Nothing Then
MsgBox "doesnt exist"
Else
MsgBox "exist"
End if
End sub
Note: Sheets_Name is where I ask the user to input the name, so this might not be the same for you.
I did another thing: delete a sheet only if it's exists - not to get an error if it doesn't:
Excel.DisplayAlerts = False
Dim WS
For Each WS In Excel.Worksheets
If WS.name = "Sheet2" Then
Excel.sheets("Sheet2").Delete
Exit For
End If
Next
Excel.DisplayAlerts = True
I use this function to check and return a new sheet name if needed. WSname is the desired worksheet name and WBCur is the workbook you would like to check in. I use this because there is no need for error handling and can call it whenever i am creating a new worksheet.
Public Function CheckNewWorksheetName(WSName As String, WBCur As Workbook) 'Will return New Name if needed
Dim NewWSNum As Long, A As Integer, B As Integer, WorksheetFound As Boolean
NewWSNum = 1
WorksheetFound = False
For A = 1 To WBCur.Worksheets.Count
If WBCur.Worksheets(A).Name = WSName Then
A = WBCur.Worksheets.Count
WorksheetFound = True
End If
Next A
If WorksheetFound = False Then
CheckNewWorksheetName = WSName
Else
Do While WorksheetFound = True
WorksheetFound = False
For B = 1 To WBCur.Worksheets.Count
If WBCur.Worksheets(B).Name = WSName & "_" & NewWSNum Then
B = WBCur.Worksheets.Count
WorksheetFound = True
NewWSNum = NewWSNum + 1
End If
Next B
Loop
CheckNewWorksheetName = WSName & "_" & NewWSNum
End If
End Function
I came up with an easy way to do it, but I didn't create a new sub for it. Instead, I just "ran a check" within the sub I was working on. Assuming the sheet name we're looking for is "Sheet_Exist" and we just want to activate it if found:
Dim SheetCounter As Integer
SheetCounter = 1
Do Until Sheets(SheetCounter).Name = "Sheet_Exist" Or SheetCounter = Sheets.Count + 1
SheetCounter = SheetCounter +1
Loop
If SheetCounter < Sheets.Count + 1 Then
Sheets("Sheet_Exist").Activate
Else
MsgBox("Worksheet ""Sheet_Exist"" was NOT found")
End If
I also added a pop-up for when the sheet doesn't exist.
I know it is an old post, but here is another simple solution that is fast.
Public Function worksheetExists(ByVal wb As Workbook, ByVal sheetNameStr As String) As Boolean
On Error Resume Next
worksheetExists = (wb.Worksheets(sheetNameStr).Name <> "")
Err.Clear: On Error GoTo 0
End Function
I actually had a simple way to check if the sheet exists and then execute some instruction:
In my case I wanted to delete the sheet and then recreated the same sheet with the same name but the code was interrupted if the program was not able to delete the sheet as it was already deleted
Sub Foo ()
Application.DisplayAlerts = False
On Error GoTo instructions
Sheets("NAME OF THE SHEET").Delete
instructions:
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "NAME OF THE SHEET"
End Sub

VBA Excluding items from filter when they're not always there

Im trying to automatically exclude certain items from a Pivot table, there are some customers that i dont want to ever include, ive got the following VBA which seems to exclude them, but if they are not on the data the next time i run it, it cant find them to exclude and then stops working.
is there a way to get it to ignore the customer if it cant find them and move on to the next one?
Sub Filtering()
ActiveSheet.PivotTables("PivotTable2").PivotFields("CUSTOMER NAME"). _
CurrentPage = "(All)"
With ActiveSheet.PivotTables("PivotTable2").PivotFields("CUSTOMER NAME")
.PivotItems("Customer1").Visible = False
.PivotItems("Customer2").Visible = False
.PivotItems("Customer3").Visible = False
End With
End Sub
is there a way to get it to ignore the customer if it cant find them and move on to the next one?
Two ways I can quickly think of. Take your pick :)
WAY 1
Check if the pivot item exists and then try to work with it. Also it is best if you use Objects. Easy to manage your code.
Is this what you are trying?
Option Explicit
Dim pField As PivotField
Sub Filtering()
Dim ws As Worksheet
'~~> Change this to relevant sheet
Set ws = Sheet1
Dim pTbl As PivotTable
Set pTbl = ws.PivotTables("PivotTable2")
Set pField = pTbl.PivotFields("CUSTOMER NAME")
pField.CurrentPage = "(All)"
With pField
If DoesPivotItemExist("Customer1") Then .PivotItems("Customer1").Visible = False
If DoesPivotItemExist("Customer4") Then .PivotItems("Customer4").Visible = False
If DoesPivotItemExist("Customer3") Then .PivotItems("Customer3").Visible = False
End With
End Sub
'~~> Function to check if the pivot item exists
Private Function DoesPivotItemExist(pvtItem As String) As Boolean
Dim pitm As PivotItem
For Each pitm In pField.PivotItems
If pitm.Name = pvtItem Then
DoesPivotItemExist = True
Exit For
End If
Next pitm
End Function
WAY 2
Use On Error Resume Next and On Error GoTo 0 to hide the item without checking if they exist or not
For example
Option Explicit
Dim pField As PivotField
Sub Filtering()
Dim ws As Worksheet
'~~> Change this to relevant sheet
Set ws = Sheet1
Dim pTbl As PivotTable
Set pTbl = ws.PivotTables("PivotTable2")
Set pField = pTbl.PivotFields("CUSTOMER NAME")
pField.CurrentPage = "(All)"
With pField
HidePivotItem "Customer1"
HidePivotItem "Customer2"
HidePivotItem "Customer4"
End With
End Sub
Private Sub HidePivotItem(pvtItem As String)
On Error Resume Next
pField.PivotItems(pvtItem).Visible = False
On Error GoTo 0
End Sub

Delete worksheets if cells below specified strings are empty

I am trying to write a script which will cycle through the worksheets in my workbook and delete the worksheet if the cells directly under the strings "detected", "not detected" and "other" are empty. If there is something entered under any of the three strings the worksheet shouldn't be deleted.
I have some code (below) which will delete the worksheet if a specific cell is empty, but I need to integrate a piece to FIND any of the three strings (if they are there, they will be in column A), and to offset this to check whether the cell below is empty.
Sub DeleteEmptyWorksheets()
Dim MySheets As Worksheet
Application.DisplayAlerts = False
For Each MySheets In ActiveWorkbook.Worksheets
If MySheets.Range(“A1”) = “” Then
MySheets.Delete
End If
Next
Application.DisplayAlerts = True
End Sub
The script will be used in processing COVID19 test results, so if you can help it will be extra karma points!!
Thankyou.
Here's a code that should assist you.
Sub DeleteEmptyWorksheets()
Dim MySheets As Worksheet
Dim rngTest As Range
Dim arTest
Dim blNBFound As Boolean
arTest = Array("detected", "not detected", "other")
Application.DisplayAlerts = False
For Each MySheets In ActiveWorkbook.Worksheets
blNBFound = False
For i = LBound(arTest) To UBound(arTest)
Set rngTest = MySheets.Range("A:A").Find(arTest(i))
If Not rngTest Is Nothing Then
If Len(rngTest.Offset(1, 0)) > 0 Then
blNBFound = True
Exit For
End If
End If
Next i
If blNBFound = False Then MySheets.Delete
Next
Application.DisplayAlerts = True
End Sub

How to create a sheet if it doesn't exist already?

I'm using the following code to check in a workbook whether sheet1 and sheet2 exist or not. If they do not exist then they're supposed to be generated. Otherwise, nothing should happen.
My problem is the macro only works for the first iteration when neither of the worksheets exists. Once the worksheets are created I get an error. Something like "Name already exists. Choose a different one…." I don't want anything to happen if sheet1 and sheet2 already exist.
Sub Worksheet()
Dim x As Integer, blnFound1 As Boolean, blnFound2 As Boolean
blnFound1 = False
blnFound2 = False
With ThisWorkbook
For x = 1 To .Sheets.Count
If .Sheets(x).Name = "Sheet1" Then
blnFound1 = True
Exit For
End If
If .Sheets(x).Name = "Sheet2" Then
blnFound2 = True
Exit For
End If
Next x
If blnFound1 = False Then
.Sheets.Add
With ActiveSheet
.Name = "Sheet1"
End With
End If
If blnFound2 = False Then
.Sheets.Add
With ActiveSheet
.Name = "Sheet2"
End With
End If
End With
End Sub
I use a different macro on every project to handle this, so you can use it whenever you want:
Sub TestSheet(SheetName As String)
Dim Exists As Boolean
With ThisWorkbook
On Error Resume Next
Exists = (.Worksheets(SheetName).Name <> "")
On Error GoTo 0
If Not Exists Then
.Sheets.Add After:=.Sheets(.Sheets.Count)
.Sheets(.Sheets.Count).Name = SheetName
End If
End With
End Sub
This is how you test:
Sub Test()
TestSheet "Sheet1"
TestSheet "Sheet2"
End Sub
What if you want to use the new Worksheet only if it didn't exist?
In that scenario, I would use a Try-Parse Pattern.
To do this, create a function that takes in the sheet name and a ByRef parameter that can return your newly created worksheet object.
Public Function TryCreateWorksheet(ByVal SheetName As String, Optional ByRef outWorksheet As Worksheet, Optional ByRef Source As Workbook) As Boolean
'If workbook not passed in then set it to the activeworkbook.
If Source Is Nothing Then
Set Source = ActiveWorkbook
End If
If Not WorksheetExists(SheetName, Source) Then
'Return true, then set outWorksheet to created worksheet and rename it.
TryCreateWorksheet = True
Set outWorksheet = Source.Worksheets.Add(After:=Source.Worksheets(Source.Worksheets.Count))
outWorksheet.Name = SheetName
End If
End Function
Here is the function for checking if the worksheet exists. It's good to be explicit in which Workbook you want to check so you don't run into any errors.
Public Function WorksheetExists(ByVal SheetName As String, ByRef Source As Workbook) As Boolean
On Error Resume Next
WorksheetExists = (Source.Worksheets(SheetName).Name <> "")
On Error GoTo 0
End Function
How to use it?
If the worksheet is created then the function returns true and you can safely know you have a reference to your new worksheet.
You could use this in an if statement to see if it returns true. If so, you can now use your worksheet object. See below:
Private Sub SomeProcedure()
Dim CreatedWs As Worksheet
If TryCreateWorksheet("Sheet3", CreatedWs, ActiveWorkbook) = False Then
MsgBox "Sheet already exists", vbInformation
Exit Sub
End If
'Do Something with your created Ws
Debug.Print CreatedWs.Name
End Sub
What if you'd like a unique name when the worksheet exists?
In that case, you could add a unique index to the end of the sheet names.
For example, if you have Sheet1 the next unique name would be Sheet1 (2) and so forth.
Public Function UniqueSheetName(ByVal Name As String, ByRef Source As Workbook) As String
'Used to create a new unique name
Dim NewName As String
NewName = Name
'Used to increment the name index. ie: Sheet1(1)
Dim Index As Integer
Index = 1
NameLoop:
'If exists then change name to include increment (n)
If WorksheetExists(NewName, Source) Then
Index = Index + 1
NewName = Name & " (" & Index & ")"
GoTo NameLoop
End If
UniqueSheetName = NewName
End Function

Test or check if sheet exists

Dim wkbkdestination As Workbook
Dim destsheet As Worksheet
For Each ThisWorkSheet In wkbkorigin.Worksheets
'this throws subscript out of range if there is not a sheet in the destination
'workbook that has the same name as the current sheet in the origin workbook.
Set destsheet = wkbkdestination.Worksheets(ThisWorkSheet.Name)
Next
Basically I loop through all sheets in the origin workbook then set destsheet in the destination workbook to the sheet with the same name as the currently iterated one in the origin workbook.
How can I test if that sheet exists? Something like:
If wkbkdestination.Worksheets(ThisWorkSheet.Name) Then
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
I wrote this one:
Function sheetExist(sSheet As String) As Boolean
On Error Resume Next
sheetExist = (ActiveWorkbook.Sheets(sSheet).Index > 0)
End Function
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") ...
Corrected:
Without error-handling:
Function CheckIfSheetExists(SheetName As String) As Boolean
CheckIfSheetExists = False
For Each WS In Worksheets
If SheetName = WS.name Then
CheckIfSheetExists = True
Exit Function
End If
Next WS
End Function
In case anyone wants to avoid VBA and test if a worksheet exists purely within a cell formula, it is possible using the ISREF and INDIRECT functions:
=ISREF(INDIRECT("SheetName!A1"))
This will return TRUE if the workbook contains a sheet called SheetName and FALSE otherwise.
Compact wsExists function (without reliance on Error Handling!)
Here's a short & simple function that doesn't rely on error handling to determine whether a worksheet exists (and is properly declared to work in any situation!)
Function wsExists(wsName As String) As Boolean
Dim ws: For Each ws In Sheets
wsExists = (wsName = ws.Name): If wsExists Then Exit Function
Next ws
End Function
Example Usage:
The following example adds a new worksheet named myNewSheet, if it doesn't already exist:
If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"
More Information:
MSDN : For Each…Next Statement (VBA)
MSDN : Exit Statement (VBA)
MSDN : Comparison Operators (VBA)
My solution looks much like Tims but also works in case of non-worksheet sheets - charts
Public Function SheetExists(strSheetName As String, Optional wbWorkbook As Workbook) As Boolean
If wbWorkbook Is Nothing Then Set wbWorkbook = ActiveWorkbook 'or ThisWorkbook - whichever appropriate
Dim obj As Object
On Error GoTo HandleError
Set obj = wbWorkbook.Sheets(strSheetName)
SheetExists = True
Exit Function
HandleError:
SheetExists = False
End Function
.
Many years late, but I just needed to do this and didn't like any of the solutions posted... So I made one up, all thanks to the magic of (SpongeBob rainbow hands gesture) "Evaluate()"!
Evaluate("IsError(" & vSheetName & "!1:1)")
Returns TRUE if Sheet does NOT exist; FALSE if sheet DOES exist.
You can substitute whatever range you like for "1:1", but I advise against using a single cell, cuz if it contains an error (eg, #N/A), it will return True.
Short and clean:
Function IsSheet(n$) As Boolean
IsSheet = Not IsError(Evaluate("'" & n & "'!a1"))
End Function
Put the test in a function and you will be able to reuse it and you have better code readability.
Do NOT use the "On Error Resume Next" since it may conflict with other part of your code.
Sub DoesTheSheetExists()
If SheetExist("SheetName") Then
Debug.Print "The Sheet Exists"
Else
Debug.Print "The Sheet Does NOT Exists"
End If
End Sub
Function SheetExist(strSheetName As String) As Boolean
Dim i As Integer
For i = 1 To Worksheets.Count
If Worksheets(i).Name = strSheetName Then
SheetExist = True
Exit Function
End If
Next i
End Function
Public Function WorkSheetExists(ByVal strName As String) As Boolean
On Error Resume Next
WorkSheetExists = Not Worksheets(strName) Is Nothing
End Function
sub test_sheet()
If Not WorkSheetExists("SheetName") Then
MsgBox "Not available"
Else MsgBox "Available"
End If
End Sub
Why not just use a small loop to determine whether the named worksheet exists? Say if you were looking for a Worksheet named "Sheet1" in the currently opened workbook.
Dim wb as Workbook
Dim ws as Worksheet
Set wb = ActiveWorkbook
For Each ws in wb.Worksheets
if ws.Name = "Sheet1" then
'Do something here
End if
Next
For Each Sheet In Worksheets
If UCase(Sheet.Name) = "TEMP" Then
'Your Code when the match is True
Application.DisplayAlerts = False
Sheet.Delete
Application.DisplayAlerts = True
'-----------------------------------
End If
Next Sheet
If you are a fan of WorksheetFunction. or you work from a non-English country with a non-English Excel this is a good solution, that works:
WorksheetFunction.IsErr(Evaluate("'" & wsName & "'!A1"))
Or in a function like this:
Function WorksheetExists(sName As String) As Boolean
WorksheetExists = Not WorksheetFunction.IsErr(Evaluate("'" & sName & "'!A1"))
End Function
Change "Data" to whatever sheet name you're testing for...
On Error Resume Next
Set DataSheet = Sheets("Data")
If DataSheet Is Nothing Then
Sheets.Add(after:=ActiveSheet).Name = "Data"
''or whatever alternate code you want to execute''
End If
On Error GoTo 0
Without any doubt that the above function can work, I just ended up with the following code which works pretty well:
Sub Sheet_exist ()
On Error Resume Next
If Sheets("" & Range("Sheet_Name") & "") Is Nothing Then
MsgBox "doesnt exist"
Else
MsgBox "exist"
End if
End sub
Note: Sheets_Name is where I ask the user to input the name, so this might not be the same for you.
I did another thing: delete a sheet only if it's exists - not to get an error if it doesn't:
Excel.DisplayAlerts = False
Dim WS
For Each WS In Excel.Worksheets
If WS.name = "Sheet2" Then
Excel.sheets("Sheet2").Delete
Exit For
End If
Next
Excel.DisplayAlerts = True
I use this function to check and return a new sheet name if needed. WSname is the desired worksheet name and WBCur is the workbook you would like to check in. I use this because there is no need for error handling and can call it whenever i am creating a new worksheet.
Public Function CheckNewWorksheetName(WSName As String, WBCur As Workbook) 'Will return New Name if needed
Dim NewWSNum As Long, A As Integer, B As Integer, WorksheetFound As Boolean
NewWSNum = 1
WorksheetFound = False
For A = 1 To WBCur.Worksheets.Count
If WBCur.Worksheets(A).Name = WSName Then
A = WBCur.Worksheets.Count
WorksheetFound = True
End If
Next A
If WorksheetFound = False Then
CheckNewWorksheetName = WSName
Else
Do While WorksheetFound = True
WorksheetFound = False
For B = 1 To WBCur.Worksheets.Count
If WBCur.Worksheets(B).Name = WSName & "_" & NewWSNum Then
B = WBCur.Worksheets.Count
WorksheetFound = True
NewWSNum = NewWSNum + 1
End If
Next B
Loop
CheckNewWorksheetName = WSName & "_" & NewWSNum
End If
End Function
I came up with an easy way to do it, but I didn't create a new sub for it. Instead, I just "ran a check" within the sub I was working on. Assuming the sheet name we're looking for is "Sheet_Exist" and we just want to activate it if found:
Dim SheetCounter As Integer
SheetCounter = 1
Do Until Sheets(SheetCounter).Name = "Sheet_Exist" Or SheetCounter = Sheets.Count + 1
SheetCounter = SheetCounter +1
Loop
If SheetCounter < Sheets.Count + 1 Then
Sheets("Sheet_Exist").Activate
Else
MsgBox("Worksheet ""Sheet_Exist"" was NOT found")
End If
I also added a pop-up for when the sheet doesn't exist.
I know it is an old post, but here is another simple solution that is fast.
Public Function worksheetExists(ByVal wb As Workbook, ByVal sheetNameStr As String) As Boolean
On Error Resume Next
worksheetExists = (wb.Worksheets(sheetNameStr).Name <> "")
Err.Clear: On Error GoTo 0
End Function
I actually had a simple way to check if the sheet exists and then execute some instruction:
In my case I wanted to delete the sheet and then recreated the same sheet with the same name but the code was interrupted if the program was not able to delete the sheet as it was already deleted
Sub Foo ()
Application.DisplayAlerts = False
On Error GoTo instructions
Sheets("NAME OF THE SHEET").Delete
instructions:
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "NAME OF THE SHEET"
End Sub

Resources