Excel VBA如果工作表(“wsName”)存在

我想知道是否有干净的切割function返回True或False如果工作簿内的工作簿存在?

如果可以在不跳过error handling的情况下做到这一点,那将是好事,但不是必须的。

我发现的唯一的东西并不真正的工作:

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 

没有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 

没有内置的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 

也是一个稍微不同的版本。 我只是做了appllication.sheets.count知道有多less工作表我额外。 好,并把一些重命名

 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 

该函数的另一个版本没有error handling。 这一次不区分大小写,效率更高一点。

 Function WorksheetExists(wsName As String) As Boolean Dim ws As Worksheet Dim ret As Boolean ret = False 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