VBA to Check if Worksheet Exists in A Workbook

juan4412

Board Regular
Joined
Oct 17, 2011
Messages
94
I have an array that opens a workbook containing close to 100 worksheets, and copies specific sheet names into there own individual workbooks. The problem I have now, is that I assume the worksheet exists in the workbook, but often times it does not :( Is there a way to add some sort of "catch" that will 1st verify the worksheet exists instead of my code crashing?
 
Try

Code:
Dim varBooks
Dim varbook
Dim varsheet
Dim varsheets(0 To 2) As String
Dim ws As Excel.Worksheet
Dim wb As Excel.Workbook
Dim i
 varsheets(0) = "Rain"
 varsheets(1) = "Sunshine"
 varsheets(2) = "Snow"
Set wb = Workbooks.Open(Filename:="R:\Weather.xls", ReadOnly:=True)
For i = LBound(varsheets) To UBound(varsheets)
    If WorksheetExists(varsheets(i)) Then
        With wb.Sheets(varsheets(i))
            .Copy
            ActiveWorkbook.SaveAs Filename:="O:\WeatherReport" & .Name & VBA.Format(Date, "mmddyyyy") & ".xls"
        End With
    End If
Next i
 
Upvote 0

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
This will open and save the 1st sheet in the array, and then it stops. It does not proceed past that point...
 
Upvote 0
It should copy all the matching sheets. Do you get an error message?
 
Upvote 0
I'm with JO -

It compiles fine, no debug error. Just saves the 1st file in the array, and then sits there.
 
Upvote 0
The function WorksheetExists might be looking for the worksheet in the wrong workbook.
 
Upvote 0
This is the function:
Code:
Function WorksheetExists(WSName As String) As Boolean On Error Resume Next WorksheetExists = Worksheets(WSName).Name = WSName On Error GoTo 0 End Function

I do not see where it is pointing to a worksheet?
</pre>
 
Upvote 0
In the code it points to a worksheet with the name passed to it.
Rich (BB code):
Function WorksheetExists(WSName As String) As Boolean
On Error Resume Next
WorksheetExists = Worksheets(WSName).Name = WSName
On Error GoTo 0
End Function

However it doesn't point to a workbook, so it will be trying to see if the worksheet exists in the active workbook.

As far as I can see the active workbook when it's called after copying the first worksheet is the new workbook that's been created.

So the WorksheetExists function returns false because the worksheet it's looking for isn't in the active workbook.

Try this.
Rich (BB code):
Option Explicit
Sub test()
Dim varBooks
Dim varbook
Dim varsheet
Dim varsheets(0 To 2) As String
Dim ws As Excel.Worksheet
Dim wb As Excel.Workbook
Dim i
    varsheets(0) = "Rain"
    varsheets(1) = "Sunshine"
    varsheets(2) = "Snow"
    Set wb = ThisWorkbook
    For i = LBound(varsheets) To UBound(varsheets)
        If WorksheetExists(wb.Name, varsheets(i)) Then
            With wb.Sheets(varsheets(i))
                .Copy
                ActiveWorkbook.SaveAs Filename:="C:\WeatherReport" & .Name & VBA.Format(Date, "mmddyyyy") & ".xls"
            End With
        End If
    Next i
End Sub
Function WorksheetExists(WBName As String, WSName As String) As Boolean
    On Error Resume Next
    WorksheetExists = Workbooks(WBName).Worksheets(WSName).Name = WSName
    On Error GoTo 0
End Function
 
Upvote 0
I haven't gone through 3 pages of discussion on what should be a (relatively) simple issue. {grin}

Maybe, someone has already given you an approach similar to the below and it doesn't meet your requirements but it appears that it should.

Try the untested

Code:
Option Explicit
Sub copySheets1()

    Dim varSheets: varSheets = Array("Rain", "Sunshine", "Snow")
     
    Dim WB As Excel.Workbook
    Set WB = Workbooks.Open(Filename:="R:\Weather.xls", ReadOnly:=True)
    
    Dim varSheet
    For Each varSheet In varSheets
        On Error Resume Next
        Dim WS As Object
        Set WS = Nothing: Set WS = WB.Sheets(varSheet)
        On Error GoTo 0
        If Not WS Is Nothing Then
            With WS
            .Copy
            ActiveWorkbook.SaveAs _
                Filename:="O:\WeatherReport" & .Name _
                    & VBA.Format(Date, "mmddyyyy") & ".xls"
            Application.DisplayAlerts = False
            ActiveWorkbook.Close False
            Application.DisplayAlerts = True
                End With
            End If
        Next varSheet
    End Sub
How would I incorporate that into my current code:
Code:
Dim varBooks
Dim varbook
Dim ws As Excel.Worksheet
Dim wb As Excel.Workbook
 
varSheets = Array("Rain", "Sunshine", "Snow")
 
For Each varSheet In varSheets
    Set wb = Workbooks.Open(Filename:="R:\Weather.xls", ReadOnly:=True)
    With wb.Sheets(varSheet)
        .Copy
        ActiveWorkbook.SaveAs Filename:="O:\WeatherReport" & .Name & VBA.Format(Date, "mmddyyyy") & ".xls"
    End With
Next varSheet

And also if the sheet does not exist, is there a way to "do nothing" and just continue processing like normal?
 
Upvote 0

Forum statistics

Threads
1,216,137
Messages
6,129,093
Members
449,486
Latest member
malcolmlyle

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top