提问人:yse 提问时间:7/14/2011 最后编辑:BigBenyse 更新时间:6/10/2023 访问量:700188
测试或检查工作表是否存在
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
基本上,我遍历原始工作簿中的所有工作表,然后在目标工作簿中设置为与原始工作簿中当前迭代的工作表同名的工作表。destsheet
如何测试该表是否存在?像这样:
If wkbkdestination.Worksheets(ThisWorkSheet.Name) Then
答:
有些人不喜欢这种方法,因为“不恰当地”使用错误处理,但我认为它在 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
评论
ActiveWorkbook
ThisWorkbook
ActiveWorkbook
sht Is Nothing
如果没有具有该名称的工作表,则为 ,但如果有具有该名称的工作表,我们希望返回,因此 Not。如果你重新排列一点,它会更容易一些(但无效)True
True
SheetExists = sht Is Not Nothing
If wb Is Nothing Then Set wb = ThisWorkbook
If wb Is Nothing Then Set wb = ActiveWorkbook
由于检查集合的成员是一个普遍问题,以下是 @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
此函数可用于任何集合,如对象 (、 、 等)。Shapes
Range
Names
Workbooks
要检查工作表是否存在,请使用If Contains(Sheets, "SheetName") ...
评论
Set
Set
TypeName
TypeName objCollection(strName)
Sub Test() On Error GoTo errhandler Debug.Print Contains(Workbooks, "SomeBookThatIsNotOpen") errhandler: If Err.Number <> 0 Then Stop End Sub
您不需要错误处理即可完成此操作。您所要做的就是遍历所有工作表并检查指定的名称是否存在:
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 并测试工作表是否纯粹存在于单元格公式中,则可以使用 和 函数:ISREF
INDIRECT
=ISREF(INDIRECT("SheetName!A1"))
如果工作簿包含名为 and 的工作表,则将返回此值。TRUE
SheetName
FALSE
毫无疑问,上述函数可以工作,我最终得到了以下运行良好的代码:
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()”的魔力!
Evaluate("IsError(" & vSheetName & "!1:1)")
如果 Sheet 不存在,则返回 TRUE;如果工作表确实存在,则为 FALSE。 您可以用您喜欢的任何范围来代替“1:1”,但我建议不要使用单个单元格,因为如果它包含错误(例如,#N/A),它将返回 True。
评论
1:1
Evaluate("IsError(Cell(""col"",'" + vSheetName + "'!A1))")
If Evaluate("IsError(Cell(""col"",'" + vSheetName + "'!A1))") Then Exit Sub
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
如果您是非英语 Excel 的粉丝或您在非英语国家/地区工作,这是一个很好的解决方案,有效:WorksheetFunction.
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
评论
sheetExist = ActiveWorkbook.Sheets(sSheet).Index
紧凑的功能(不依赖错误处理!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"
更多信息:
- MSDN:
对于每个
...下一个
语句 (VBA) - MSDN:
退出
声明 (VBA) - MSDN:比较运算符 (VBA)
我想出了一个简单的方法来做到这一点,但我没有为它创建一个新的潜艇。相反,我只是在我正在处理的潜艇中“运行了一次检查”。假设我们要查找的工作表名称是“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
无需循环或使用我能看到的函数?
如果 wkbkdestination.工作表(ThisWorkSheet.Name)。name = ThisWorksheet.Name 然后
“做事
还
'转到循环的末尾
如果结束
评论