ray88’s diary

お仕事で困ったとき用の自分用の覚書

Excel VBA ブック内のシートを調べる

Function fncSheetExsists(strPath, strTargetSheetName As String) As Boolean
'------------------------------------------------------------------------
'機能1:渡されたブックのシート全てを調べ、特定の値のシート名の有無を返す
'引数1:確認するブックのパス
'引数2:検索対象のシート名
'------------------------------------------------------------------------
    'フラグを初期化
    fncSheetExsists = False
'------------------------------------------------------
    Dim wb As Workbook
    Dim shCount As Integer
    Dim sh As Variant
 '-----------------------------------------------------
    Set wb = Workbooks.Open(strParentFolderPath & "\" & strSubFolderName & "\" & strPath)
    'ファイル内のシート数を取得
    shCount = wb.Sheets.Count
    
    '全シート分、該当シート名が見つかるまで繰り返し処理
    For Each sh In wb.Sheets
        '該当シート名が存在したらループを抜ける
        If sh.Name = strTargetSheetName Then
            fncSheetExsists = True
            Exit For
        End If
    Next
    wb.Close
    Set wb = Nothing
End Function