Workbook_BeforeClose compile error: Variable not defined help

Pookiemeister

Well-known Member
Joined
Jan 6, 2012
Messages
623
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

Links? Where??
If Excel says you have links but you can't find them, go to Formulas, Name Manager. Look for old links to dead workbooks & delete.
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,220,965
Messages
6,157,119
Members
451,398
Latest member
rjsteward

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