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
 

Some videos you may like

Excel Facts

Copy a format multiple times
Select a formatted range. Double-click the Format Painter (left side of Home tab). You can paste formatting multiple times. Esc to stop

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
46,010
Office Version
  1. 365
Platform
  1. Windows
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
 

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
46,010
Office Version
  1. 365
Platform
  1. Windows
You're welcome & thanks for the feedback
 

Watch MrExcel Video

Forum statistics

Threads
1,108,507
Messages
5,523,308
Members
409,509
Latest member
CheekyDevil2386

This Week's Hot Topics

Top