首页 > 解决方案 > VBA如果工作表存在继续代码

问题描述

尽管这似乎是一个常见问题,但我没有找到对我的问题有用的东西。我有一个简单的旧代码,其中一张表中有一张公司数据表。我的代码根据公司名称获取数据,在工作簿中找到具有该公司名称的工作表并执行少量操作。

当其中一张纸被删除并且代码卡住时,我的问题就开始了。我在代码中为每家公司执行相同的例程,如果它没有找到具有特定公司名称的工作表,我希望它将它用于下一家公司。

有人可以提供一些可以作为if声明的东西吗?

这是代码的开头,例如两家公司 - YEDIDIM 和 BEHIRIM。其他是一样的:

Sub Calculation_of_Change()

Application.ScreenUpdating = False

'refresh 2 PivoTableS
Dim pivot As PivotTable
Set pivot = Worksheets("PIVOT").PivotTables("PivotTable1")
pivot.RefreshTable
Set pivot = Sheets("PIVOT (-)").PivotTables("PivotTable1")
pivot.RefreshTable

'we need to delete the old data and replace it with new data

'YEDIDIM
'first we will delete all old data
Sheets("YEDIDIM").Select
Range("A2", Range("A2").End(xlDown)).Select
Selection.EntireRow.Delete


'for each sheet with data we will filter the PIVOT table and paste the new data so we could calculate the stats we want
    Sheets("PIVOT").Activate
    ActiveSheet.PivotTables("PivotTable1").PivotFields("ùí úú îôòì"). _
        ClearAllFilters
    ActiveSheet.PivotTables("PivotTable1").PivotFields("ùí úú îôòì").PivotFilters. _
        Add2 Type:=xlCaptionContains, Value1:="YEDIDIM"

    Range("A5", Range("A5").End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Copy
    Sheets("YEDIDIM").Select
    Range("A2").PasteSpecial (xlPasteValues)


'BEHIRIM
'first we will delete all old data
Sheets("BEHIRIM").Select
Range("A2", Range("A2").End(xlDown)).Select
Selection.EntireRow.Delete


'for each sheet with data we will filter the PIVOT table and paste the new data so we could calculate the stats we want
Sheets("PIVOT").Activate
    ActiveSheet.PivotTables("PivotTable1").PivotFields("ùí úú îôòì"). _
        ClearAllFilters
    ActiveSheet.PivotTables("PivotTable1").PivotFields("ùí úú îôòì").PivotFilters. _
        Add2 Type:=xlCaptionContains, Value1:="BEHIRIM"

    Range("A5", Range("A5").End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Copy
    Sheets("BEHIRIM").Select
    Range("A2").PasteSpecial (xlPasteValues)

标签: excelvba

解决方案


这是WorksheetExists()通常使用的功能:

Function WorksheetExists(sheetName As String) As Boolean        
    WorksheetExists = Not WorksheetFunction.IsErr(Evaluate("'" & sheetName & "'!A1"))
End Function

为了您的目标,它可以这样使用:

If Not WorksheetExists("NameOfTheWorksheet") Then Exit Sub

推荐阅读