[英]How to check the availability of a worksheet
I have to run a set of code related to worksheet " wins ", but only if that worksheet exist.我必须运行一组与工作表“ wins ”相关的代码,但前提是该工作表存在。
Please share a code to check the availability of sheet "wins".请共享代码以检查“获胜”表的可用性。 If worksheet "wins" exist, then only I want to run that set of code, else I want to skip executing that set of code and move to next line of code.
如果工作表“获胜”存在,那么我只想运行该组代码,否则我想跳过执行该组代码并移至下一行代码。
You could use On Error Resume Next
to skip the errror which occurs if you try access a not existing worksheet and assigning it to a object variable.如果您尝试访问不存在的工作表并将其分配给对象变量,则可以使用
On Error Resume Next
跳过发生的On Error Resume Next
。 So if the worksheet does not exist, no error occurs but the variable is Nothing
.因此,如果工作表不存在,则不会发生错误,但变量为
Nothing
。 If the worksheet exists, then the variable is not Nothing
.如果工作表存在,则变量不是
Nothing
。
Example:例子:
Sub test()
Dim wsWins As Worksheet
On Error Resume Next
Set wsWins = ActiveWorkbook.Worksheets("wins")
On Error GoTo 0
If Not wsWins Is Nothing Then
MsgBox "Worksheet wins exists."
Else
MsgBox "Worksheet wins does not exist."
End If
End Sub
Axel's answer will work nicely.阿克塞尔的回答会很好地工作。 Some people prefer not to use error throwing to test if something exists.
有些人不喜欢使用错误抛出来测试某些东西是否存在。 If you're one of them then I use the following quite a lot in a Utility module.
如果您是其中之一,那么我会在实用程序模块中大量使用以下内容。 It'll work for Worksheets, Charts, etc. (basically anything that's a collection with a 'Name' property):
它适用于工作表、图表等(基本上任何具有“名称”属性的集合):
Public Function ExcelObjectExists(testName As String, excelCollection As Object) As Boolean
Dim item As Object
On Error GoTo InvalidObject
For Each item In excelCollection
If item.Name = testName Then
ExcelObjectExists = True
Exit Function
End If
Next
ExcelObjectExists = False
Exit Function
InvalidObject:
MsgBox "Developer error: invalid collection object passed in ExcelObjectExists."
ExcelObjectExists = False
End Function
You can call it like this:你可以这样称呼它:
If ExcelObjectExists("wins", ThisWorkbook.Worksheets) Then
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.