如果存在代码,请删除工作表

时间:2016-05-13 15:26:44

标签: excel-vba vba excel

我已经编写了一些VBA代码来查看是否存在工作表,是否删除了它,然后恢复了另一个代码模块。出于某种原因,我在下面的代码没有做任何事情,我无法弄清楚原因。

Sub delete()
    Dim ws As Worksheet

    If worksheetexists("Export Worksheet") Then
        Set ws = Worksheets("Export Worksheet")        
        Application.DisplayAlerts = False        
        ws.delete        
        Call GetData        
    Else
        Call GetData
    End If

End Sub

Public Function worksheetexists(sheetname As String, Optional wrkbk As Workbook) As Boolean
    Dim wrksht As Worksheet

    If wrkbk Is Nothing Then
        Set wrkbk = ActiveWorkbook        
    End If

    On Error Resume Next

    Set wrksht = wrkbk.Worksheets(sheetname)
    worksheetexists = (Err.Number = 0)
    Set wrksht = Nothing

    On Error GoTo 0
End Function

2 个答案:

答案 0 :(得分:0)

我稍微更新了你的代码:

Sub delete()
    Dim ws As Worksheet

    If worksheetexists("Export Worksheet") Then
        Set ws = Worksheets("Export Worksheet")
        Application.DisplayAlerts = False
        ws.delete
        Call GetData("pass")
    Else
        Call GetData("fail")
    End If

End Sub

并将其用于GetData()

Sub GetData(s)
    MsgBox s
End Sub

它适用于传递失败案例。检查工作表名称的拼写............................ 特别是空格数。

答案 1 :(得分:0)

@BriannaCates,bellow的功能对我有用,也许适合你。

Public Function deleteWorksheet(sheet As String, Optional work As Workbook) As Boolean
    Dim ws As Worksheet
    Dim deleted As Boolean

    If work Is Nothing Then
        Set work = ThisWorkbook
    End If

    deleted = False
    For Each ws In work.Worksheets
        If ws.Name = sheet Then
            ws.Delete
            deleted = True
            Exit For
        End If
    Next

    deleteWorksheet = deleted

End Function