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

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
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,224,824
Messages
6,181,186
Members
453,020
Latest member
Mohamed Magdi Tawfiq Emam

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