excel - 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)
解决方案
这是WorksheetExists()
我通常使用的功能:
Function WorksheetExists(sheetName As String) As Boolean
WorksheetExists = Not WorksheetFunction.IsErr(Evaluate("'" & sheetName & "'!A1"))
End Function
为了您的目标,它可以这样使用:
If Not WorksheetExists("NameOfTheWorksheet") Then Exit Sub
推荐阅读
- plsql - 使用 UTL_HTTP 连接到供应商服务器的问题
- android - 导航项更改不会更新回收站视图
- c# - C# 类的嵌套数组
- docker - 通过服务在 kind kubernetes 集群中暴露一个 kubernetes pod
- java - 如何应用选择方法按字母顺序排序?
- amazon-web-services - 我正在设置 aws Okta,在其中一个步骤中我看到了这个 ~/.aws/config:
- mysql - 仅从 mariadb 表中获取精确匹配的行
- c++ - 函数指针成员变量
- java - javax.xml.ws.WebServiceException:方法X暴露为WebMethod,但是没有对应的wsdl操作
- java - 将 apache mina 从 2.0.21 升级到 2.1.3 后 ldap 测试出现问题