Workbook_BeforeClose compile error: Variable not defined help

Pookiemeister

Well-known Member
Joined
Jan 6, 2012
Messages
626
Office Version
  1. 365
  2. 2010
Platform
  1. Windows
What this code is suppose to do is look to see if any of the worksheet names equals Exhibit "I" or "page 2". If they do exist then before closing the workbook don't save it and then close the workbook.

Actual First Worksheet Name is Exhibit "I" and the second worksheet name is page 2.

Unfortunately, I am getting a compile error: Variable not defined and the following word "Worksheet" is highlighted in blue.

Code:
If [COLOR=#0000FF][B]Worksheet[/B][/COLOR].Name = ("Exhibit 'I'") Or ("page 2") Then

Full Code Below:
Code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)    
    If Worksheet.Name = ("Exhibit 'I'") Or ("page 2") Then
        ThisWorkbook.Save = False
        ThisWorkbook.Close
    End If
    
End Sub

Thank You
 
Last edited:

Excel Facts

Will the fill handle fill 1, 2, 3?
Yes! Type 1 in a cell. Hold down Ctrl while you drag the fill handle.
Untested and assuming the sheet names in your description is correct...

Code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
    If ws.Name = "Exhibit ""I""" Or ws.Name = "page 2" Then
        ThisWorkbook.Save = False
        ThisWorkbook.Close
    End If
 Next
End Sub
 
Last edited:
Upvote 0
Try this

Code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Sheets
        If ws.Name = "Exhibit ""I""" Or ws.Name = "page 2" Then
            Application.DisplayAlerts = False
            ThisWorkbook.Close
            Application.DisplayAlerts = True
            Exit For
        End If
    Next
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,909
Messages
6,175,310
Members
452,634
Latest member
cpostell

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