Test or check if sheet exists

Dim wkbkdestination As Workbook
Dim destsheet As Worksheet


For Each ThisWorkSheet In wkbkorigin.Worksheets
'this throws subscript out of range if there is not a sheet in the destination
'workbook that has the same name as the current sheet in the origin workbook.
Set destsheet = wkbkdestination.Worksheets(ThisWorkSheet.Name)
Next

Basically I loop through all sheets in the origin workbook then set destsheet in the destination workbook to the sheet with the same name as the currently iterated one in the origin workbook.

How can I test if that sheet exists? Something like:

If wkbkdestination.Worksheets(ThisWorkSheet.Name) Then
648334 次浏览

有些人不喜欢这种方法,因为错误处理的使用“不恰当”,但是我认为它在 VBA 中是可以接受的... ... 另一种方法是循环遍历所有表,直到找到匹配。

Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet


If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
WorksheetExists = Not sht Is Nothing
End Function

由于检查一个集合的成员是一个普遍的问题,下面是@Tim 的答案的一个抽象版本:

Function Contains(objCollection As Object, strName as String) As Boolean
Dim o as Object
On Error Resume Next
set o = objCollection(strName)
Contains = (Err.Number = 0)
Err.Clear
End Function

这个函数可以与任何类似对象的集合(ShapesRangeNamesWorkbooks等)一起使用。

若要检查是否存在工作表,请使用 If Contains(Sheets, "SheetName") ...

您不需要为了完成这个任务而进行错误处理。您所要做的就是遍历所有的工作表,并检查指定的名称是否存在:

Dim exists As Boolean


For i = 1 To Worksheets.Count
If Worksheets(i).Name = "MySheet" Then
exists = True
End If
Next i


If Not exists Then
Worksheets.Add.Name = "MySheet"
End If
Public Function WorkSheetExists(ByVal strName As String) As Boolean
On Error Resume Next
WorkSheetExists = Not Worksheets(strName) Is Nothing
End Function


sub test_sheet()


If Not WorkSheetExists("SheetName") Then
MsgBox "Not available"
Else MsgBox "Available"
End If


End Sub

将测试放在函数中,您将能够重用它,并且具有更好的代码可读性。

不要使用“ On Error Resume Next”,因为它可能与代码的其他部分冲突。

Sub DoesTheSheetExists()
If SheetExist("SheetName") Then
Debug.Print "The Sheet Exists"
Else
Debug.Print "The Sheet Does NOT Exists"
End If
End Sub


Function SheetExist(strSheetName As String) As Boolean
Dim i As Integer


For i = 1 To Worksheets.Count
If Worksheets(i).Name = strSheetName Then
SheetExist = True
Exit Function
End If
Next i
End Function

我实际上有一个简单的方法来检查表是否存在,然后执行一些指令:

在我的例子中,我想删除工作表,然后用相同的名称重新创建相同的工作表,但是如果程序不能删除工作表,代码就会被中断,因为它已经被删除了

Sub Foo ()


Application.DisplayAlerts = False


On Error GoTo instructions
Sheets("NAME OF THE SHEET").Delete


instructions:


Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "NAME OF THE SHEET"


End Sub

我的解决方案看起来很像 Tims,但在非工作表-图表的情况下也有效

Public Function SheetExists(strSheetName As String, Optional wbWorkbook As Workbook) As Boolean
    If wbWorkbook Is Nothing Then Set wbWorkbook = ActiveWorkbook 'or ThisWorkbook - whichever appropriate
    Dim obj As Object
    On Error GoTo HandleError
    Set obj = wbWorkbook.Sheets(strSheetName)
    SheetExists = True
    Exit Function
HandleError:
    SheetExists = False
End Function

.

为什么不使用一个小循环来确定命名的工作表是否存在?假设您正在当前打开的工作簿中查找名为“ Sheet1”的工作表。

Dim wb as Workbook
Dim ws as Worksheet


Set wb = ActiveWorkbook


For Each ws in wb.Worksheets


if ws.Name = "Sheet1" then
'Do something here
End if


Next

如果您只对工作表感兴趣,可以使用一个简单的“评估”调用:

Function WorksheetExists(sName As String) As Boolean
WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function

更正: 没有错误处理:

Function CheckIfSheetExists(SheetName As String) As Boolean
CheckIfSheetExists = False
For Each WS In Worksheets
If SheetName = WS.name Then
CheckIfSheetExists = True
Exit Function
End If
Next WS
End Function

我还做了另一件事: 只删除存在的工作表——不要在它不存在的情况下得到错误:

Excel.DisplayAlerts = False
Dim WS
For Each WS In Excel.Worksheets
If WS.name = "Sheet2" Then
Excel.sheets("Sheet2").Delete
Exit For
End If
Next
Excel.DisplayAlerts = True

如果有人想避免使用 VBA 并测试工作表是否纯粹存在于单元格公式中,可以使用 ISREFINDIRECT函数:

=ISREF(INDIRECT("SheetName!A1"))

如果工作簿包含称为 SheetNameFALSE的工作表,则返回 TRUE

毫无疑问,上面的函数可以工作,我最终得到了下面的代码,它运行得很好:

Sub Sheet_exist ()
On Error Resume Next
If Sheets("" & Range("Sheet_Name") & "") Is Nothing Then
MsgBox "doesnt exist"
Else
MsgBox "exist"
End if
End sub

注意: Sheets_Name是我要求用户输入名称的地方,所以这对您来说可能不一样。

很多年后,但我只是需要这样做,不喜欢任何解决方案张贴... 所以我编造了一个,所有感谢的魔力(海绵宝宝彩虹手势)“评估()”!

Evaluate("IsError(" & vSheetName & "!1:1)")

如果工作表不存在,返回 TRUE; 如果工作表不存在,返回 FALSE。 您可以用任何您喜欢的范围替换“1:1”,但我建议不要使用单个单元格,因为如果它包含错误(例如 # N/A) ,它将返回 True。

    For Each Sheet In Worksheets
If UCase(Sheet.Name) = "TEMP" Then
'Your Code when the match is True
Application.DisplayAlerts = False
Sheet.Delete
Application.DisplayAlerts = True
'-----------------------------------
End If
Next Sheet

如果你是 WorksheetFunction.的粉丝,或者你在一个非英语国家工作,使用非英语的 Excel 表格,这是一个很好的解决方案,可以奏效:

WorksheetFunction.IsErr(Evaluate("'" & wsName & "'!A1"))

或者在这样的函数中:

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

将“数据”更改为您正在测试的工作表名称..。

On Error Resume Next


Set DataSheet = Sheets("Data")


If DataSheet Is Nothing Then


Sheets.Add(after:=ActiveSheet).Name = "Data"
''or whatever alternate code you want to execute''
End If


On Error GoTo 0

我写了这个:

Function sheetExist(sSheet As String) As Boolean
On Error Resume Next
sheetExist = (ActiveWorkbook.Sheets(sSheet).Index > 0)
End Function

紧凑型 wsExists功能

这里有一个简短而简单的函数,它不依赖于错误处理来确定工作表是否存在(在 任何的情况下,正确地声明 还有可以工作!)

Function wsExists(wsName As String) As Boolean
Dim ws: For Each ws In Sheets
wsExists = (wsName = ws.Name): If wsExists Then Exit Function
Next ws
End Function

示例用法:

下面的示例添加一个名为 myNewSheet的新工作表(如果它还不存在的话) :

If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"

更多信息:

我想出了一个简单的方法,但我没有为它创建一个新的代课老师。相反,我只是在我工作的潜艇里“检查”了一下。假设我们正在查找的工作表名称是“ Sheet _ Exist”,我们只想在找到时激活它:

Dim SheetCounter As Integer


SheetCounter = 1


Do Until Sheets(SheetCounter).Name = "Sheet_Exist" Or SheetCounter = Sheets.Count + 1
SheetCounter = SheetCounter +1
Loop
If SheetCounter < Sheets.Count + 1 Then
Sheets("Sheet_Exist").Activate
Else
MsgBox("Worksheet ""Sheet_Exist"" was NOT found")
End If

我还为表不存在时添加了一个弹出框。

我知道这是一个老职位,但这里有另一个简单的解决方案,是快速的。

Public Function worksheetExists(ByVal wb As Workbook, ByVal sheetNameStr As String) As Boolean


On Error Resume Next
worksheetExists = (wb.Worksheets(sheetNameStr).Name <> "")
Err.Clear: On Error GoTo 0


End Function

简洁明了:

Function IsSheet(n$) As Boolean
IsSheet = Not IsError(Evaluate("'" & n & "'!a1"))
End Function

如果需要,我使用这个函数检查并返回一个新的工作表名称。WSname 是所需的工作表名称,WBCur 是要签入的工作簿。我使用它是因为不需要错误处理,并且可以在创建新工作表时调用它。

Public Function CheckNewWorksheetName(WSName As String, WBCur As Workbook) 'Will return New Name if needed
Dim NewWSNum As Long, A As Integer, B As Integer, WorksheetFound As Boolean
NewWSNum = 1
WorksheetFound = False
For A = 1 To WBCur.Worksheets.Count
If WBCur.Worksheets(A).Name = WSName Then
A = WBCur.Worksheets.Count
WorksheetFound = True
End If
Next A
    

If WorksheetFound = False Then
CheckNewWorksheetName = WSName
Else
Do While WorksheetFound = True
WorksheetFound = False
For B = 1 To WBCur.Worksheets.Count
If WBCur.Worksheets(B).Name = WSName & "_" & NewWSNum Then
B = WBCur.Worksheets.Count
WorksheetFound = True
NewWSNum = NewWSNum + 1
End If
Next B
Loop
CheckNewWorksheetName = WSName & "_" & NewWSNum
End If
End Function