简体   繁体   中英

How to delete a blank sheet in a workbook using VBA?

Sub delete()
    Dim sh As Worksheet, wb As String, c As Range
    wb = InputBox("work book name")
    Set sh = Workbooks(wb).Sheets
        For Each Sheet In sh
            If IsEmpty(sh.UsedRange) Then
            sh.delete
            End If
        Next
End Sub

I am unable to delete the empty sheets using above code.

The below code deletes all empty sheets in the currently opened workbook

try this instead

Sub delete()
    Application.DisplayAlerts = False
    Dim sh As Worksheet
    For Each sh In Sheets
        If IsEmpty(sh.UsedRange) Then sh.delete
    Next
    Application.DisplayAlerts = True
End Sub

if you want to specify the full path with the name use

Sub delete()
    Dim wb As Workbook, s As String
    s = InputBox("Full workbook path & name")

    Dim fileExists As Boolean
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    fileExists = fso.fileExists(s)

    If fileExist Then
        Set wb = Workbooks.Open(s)
        For Each Sheet In sh
            If IsEmpty(sh.UsedRange) Then
            sh.delete
            End If
        Next
    Else
        MsgBox "File doesn't exist", vbCritical, "Error"
    End If

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM