Mega Code Archive

 
Categories / VisualBasic Script / Excel
 

Safely Deleting Worksheets Using the DeleteSheet Function

Function DeleteSheet(ws As Worksheet, bQuiet As Boolean) As Boolean      Dim bDeleted As Boolean      On Error GoTo ErrHandler      bDeleted = False       If CountVisibleSheets(ws.Parent) > 1 Then          If bQuiet Then Application.DisplayAlerts = False          bDeleted = ws.Parent.Worksheets(ws.Name).Delete      End If  ExitPoint:      Application.DisplayAlerts = True      DeleteSheet = bDeleted      Exit Function  ErrHandler:      bDeleted = False      Resume ExitPoint  End Function  Function CountVisibleSheets(wb As Workbook) As Integer      Dim nSheetIndex As Integer      Dim nCount As Integer      nCount = 0      For nSheetIndex = 1 To wb.Sheets.Count          If wb.Sheets(nSheetIndex).Visible = xlSheetVisible Then              nCount = nCount + 1          End If      Next      CountVisibleSheets = nCount  End Function