web-dev-qa-db-ja.com

WorkSheet( "wsName")が存在する場合、Excel VBA

ブック内にワークシートが存在する場合に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
36
Matt Rowles

エラー処理のないバージョン:

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
77
Dante May Code

これには組み込み関数はありません。

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
29
Tim Williams

また、わずかに異なるバージョン。私は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
8
jogrohs

エラー処理のない関数の別の 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
6
Erik K.

ジェネリックライブラリの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
4
ShamBhagwat