Excel VBA If WorkSheet(“wsName”) Exists [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

This question already has an answer here:

I'm wondering if there is clean cut functionality that returns True or False if a worksheet inside a workbook exists?

It would be good, but not essential, if it's possible to do it without skipping error handling.

The only thing I've found doesn't really work:

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 

回答1:

A version without error-handling:

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 


回答2:

There's no built-in function for this.

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 


回答3:

also a slightly different version. i just did a appllication.sheets.count to know how many worksheets i have additionallyl. well and put a little rename in aswell

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 


回答4:

Another version of the function without error handling. This time it is not case sensitive and a little bit more efficient.

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 


回答5:

Slightly changed to David Murdoch's code for generic library

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!