Link to home
Start Free TrialLog in
Avatar of csehz
csehzFlag for Hungary

asked on

VBA Excel 2000 - Rename sheet if that exist

Dear Experts,

In a file it can happen that there are two sheets "Domestic" and "Export", but also that any of them does not exist or just one of them.

Could you please how to write a macro which would be able to identify what is the actual scenario, and based on that rename any of them to "Total"?

With IFs would be imagined like this
- if "Domestic" exist then rename it to "Total" (if also exist "Export" than just leave it unchanged)
- if "Export" exist then rename it to "Total" (if also exist "Domestic" than just leave it unchanged)
- if any of them does not exist then add a sheet as "Total"

thanks,





ASKER CERTIFIED SOLUTION
Avatar of SiddharthRout
SiddharthRout
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of csehz

ASKER

Sid thanks very much it works, finally added a line yet if both exist


    ElseIf CheckIfSheetExist("Domestic") = True And CheckIfSheetExist("Export") = True Then
        Sheets("Export").Name = "Total"
Avatar of Dave
While I see you have close this I would do this a little differently

1) test for the existence of "Total" before causinbg an error by duplicating the name
2) you can test for the sheet names directly rather than looping through all the sheet names

Cheers

Dave
Sub SheetNames()
    Dim wsx As Worksheet
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim ws3 As Worksheet
    On Error Resume Next
    Set wsx = Sheets("Total")
    Set ws1 = Sheets("Domestic")
    Set ws1 = Sheets("Export")
    On Error GoTo 0
    If Not wsx Is Nothing Then
        MsgBox "you already have a sheet called nothing", vbCritical
        Exit Sub
    End If

    If Not ws1 Is Nothing Then
        ws1.Name = "Total"
    Else
        If Not ws2 Is Nothing Then
            ws2.Name = "Total"
        Else
            Set ws3 = Sheets.Add
            ws3.Name = "Total"
        End If
    End If
End Sub

Open in new window

Avatar of csehz

ASKER

Dave thanks, sorry that closed the topic so can not give points, your code also works and moreover automatically handles the both existing scenarios correctly which I left out from the IF listings at the question :-))
No probs :)

You closed as I was finalising the code so I'd figured I'd carry though with it

Cheers

Dave