IF sheet exists do 'x' if not show msgbox

hillmas83

New Member
Joined
Aug 23, 2017
Messages
6
Hi,

I am trying to write code which looks to see if a sheet exists called 'Copy of System Sheet' and if it does then delete 'System Sheet' and rename the copy as 'System Sheet'. (Copy of System Sheet may be hidden). If sheet 'Copy of System Sheet' does not exist then display the msgbox.

I have the below code which works the first time i press it, but if i run the code twice in a row, the second time it deletes the 'System Sheet'. I cannot figure out why. Any help much appreciated as always.


Code:
Option Explicit
Dim ws As Worksheet
Dim x As Object


Sub test()


On Error Resume Next
Set ws = Sheets("Copy of System Sheet")
On Error GoTo 0
If Not ws Is Nothing Then
    Application.DisplayAlerts = False
    Sheets("System Sheet").Delete
    Application.DisplayAlerts = True
    Sheets("Copy of System Sheet").Visible = True
    Sheets("Copy of System Sheet").Select
    ActiveSheet.Name = ("System Sheet")
    
    
Else
MsgBox "No Copy to Reinstate so i will not delete the System Sheet"
End If




End Sub
 

Excel Facts

How to change case of text in Excel?
Use =UPPER() for upper case, =LOWER() for lower case, and =PROPER() for proper case. PROPER won't capitalize second c in Mccartney
It's because you have declared ws outside the code, therefore it retains its value after the sub has finished.
Either set it back to nothing at the start of the sub
Code:
Set ws = Nothing
Or declare the variable inside the sub
 
Upvote 0
You're welcome & thanks for the feedback
 
Upvote 0

Forum statistics

Threads
1,223,909
Messages
6,175,314
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