Delete Sheet based on condition

Hi,

is been a while since i have use UiPath, i have this condition where i want to check in my excel on some particular sheet if they exist it be deleted

how can i do it ?

i have this sample excel file i wan to check Sheet A, B, C, and D
Book1.xlsx (11.5 KB)

Hey!

You should use the following activities:

Excel Process Scope > Use Excel File > For Each Excel Sheet > If > Delete Sheet

The If condition should be

CurrentSheet.Name.contains(β€œA”) or CurrentSheet.Name.contains(β€œB”) or CurrentSheet.Name.contains(β€œC”) CurrentSheet.Name.contains(β€œD”)

Hope this helps you!

1 Like

Thanks man i have forgotten about it with this it will work !

Hi @xxGoRpa

Point 1: There are few things we need to keep in mind here, since we want to delete the specified sheets, the operation need to be carried out if all/any of them are present. Along with that, if we check against SheetName.Contains property, it might delete uninteded sheets based on the letter’s presence, which is indeed a conflict.

Point 2: Let’s say your file has only 1 Sheet i.e, A. In that case you cannot delete the sheet, as a workbook must contain atleast one visible worksheet.

Thus, you can try the following VBA code to achieve the desired result:

Sub sampleMacro()
    Dim ws As Worksheet
    
    Application.DisplayAlerts = False

    If SheetExists("A") Then
        Sheets("A").Delete
    End If
    If SheetExists("B") Then
        Sheets("B").Delete
    End If
    If SheetExists("C") Then
        Sheets("C").Delete
    End If
    If SheetExists("D") Then
        Sheets("D").Delete
    End If
    
    Application.DisplayAlerts = True
    
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = "A" Or ws.Name = "B" Or ws.Name = "C" Or ws.Name = "D" Then
            MsgBox "Failed to delete one or more sheets."
            Exit Sub
        End If
    Next
    
    MsgBox "Sheets deleted successfully."
End Sub

Function SheetExists(sheetName As String) As Boolean
    SheetExists = False
    On Error Resume Next
    SheetExists = Not Sheets(sheetName) Is Nothing
End Function

Save this code in a text file, use Invoke VBA activity, provide the input file path, and mention the entry method as sampleMacro

Before:

image

After:

Hope this helps,
Best Regards.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.