Excel VBA如果WorkSheet(“wsName”)存在[重复]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Excel VBA如果WorkSheet(“wsName”)存在[重复]相关的知识,希望对你有一定的参考价值。
这个问题在这里已有答案:
我想知道如果存在工作簿中的工作表,是否存在返回True或False的清除功能?
如果可以在不跳过错误处理的情况下完成它,那将是好的,但不是必需的。
我发现的唯一的东西并不真正起作用:
On Error Resume Next
If (Worksheets("wsName").Name <> "") Then
Debug.Print "Worksheet exists!"
Else
Debug.Print "Worksheet doesn't exist!"
End If
On Error GoTo ErrHandler
答案
没有错误处理的版本:
Function sheetExists(sheetToFind As String) As Boolean
sheetExists = False
For Each sheet In Worksheets
If sheetToFind = sheet.name Then
sheetExists = True
Exit Function
End If
Next sheet
End Function
另一答案
这没有内置功能。
Function SheetExists(SheetName As String, Optional wb As Excel.Workbook)
Dim s As Excel.Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set s = wb.Sheets(SheetName)
On Error GoTo 0
SheetExists = Not s Is Nothing
End Function
另一答案
也是一个略有不同的版本。我刚刚做了一个application.sheets.count来了解我还有多少工作表。好吧,并进行一点重命名
Sub insertworksheet()
Dim worksh As Integer
Dim worksheetexists As Boolean
worksh = Application.Sheets.Count
worksheetexists = False
For x = 1 To worksh
If Worksheets(x).Name = "ENTERWROKSHEETNAME" Then
worksheetexists = True
'Debug.Print worksheetexists
Exit For
End If
Next x
If worksheetexists = False Then
Debug.Print "transformed exists"
Worksheets.Add after:=Worksheets(Worksheets.Count)
ActiveSheet.Name = "ENTERNAMEUWANTTHENEWONE"
End If
End Sub
另一答案
另一个没有错误处理功能的version。这次它不区分大小写并且效率更高一些。
Function WorksheetExists(wsName As String) As Boolean
Dim ws As Worksheet
Dim ret As Boolean
wsName = UCase(wsName)
For Each ws In ThisWorkbook.Sheets
If UCase(ws.Name) = wsName Then
ret = True
Exit For
End If
Next
WorksheetExists = ret
End Function
另一答案
稍微改为David Murdoch的通用库代码
Function HasByName(cSheetName As String, _
Optional oWorkBook As Excel.Workbook) As Boolean
HasByName = False
Dim wb
If oWorkBook Is Nothing Then
Set oWorkBook = ThisWorkbook
End If
For Each wb In oWorkBook.Worksheets
If wb.Name = cSheetName Then
HasByName = True
Exit Function
End If
Next wb
End Function
以上是关于Excel VBA如果WorkSheet(“wsName”)存在[重复]的主要内容,如果未能解决你的问题,请参考以下文章
在单个文件中的所有打开的工作簿中重新使用带有“Worksheet_Change”事件的 VBA 宏
为啥 MS Excel 在 Worksheet_Change Sub 过程中崩溃并关闭?
excel中使用vba如何能够实现如果我这个单元格里的内容是1则另一个单元格锁定,不允许修改,