0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Excel VBA 指定した文字列を検索し対象ファイルを開きます

Posted at

はじめに

指定した文字列を検索し対象ファイルを開きます

プロシジャーの説明

B列を検索対象にして、指定した文字列がフルパスに含まれている場合そのExcelファイルを開く

サンプル1

Option Explicit

Sub SearchAndOpenFile()
' -------------------------------------------------------------
' B列を検索対象にして、指定した文字列がフルパスに含まれている場合、
' そのExcelファイルを開く仕組みになっています。
' -------------------------------------------------------------

    Dim ws As Worksheet
    Dim LastRow As Long
    Dim SearchTerm As String
    Dim i As Long
    Dim FilePath As String
    
    ' 検索対象の文字列を設定
    SearchTerm = "代入"
    
    ' ワークシートを設定
    Set ws = ThisWorkbook.Sheets(1)
    
    ' B列の最終行を取得
    LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
    
    ' B列を1行目から最終行まで検索
    For i = 1 To LastRow
        FilePath = ws.Cells(i, "B").Value
        
        ' フルパスに検索対象の文字列が含まれているか確認
        If InStr(FilePath, SearchTerm) > 0 Then
            ' ファイルがExcelファイルかどうか確認
            If Right(FilePath, 5) = ".xlsx" Or Right(FilePath, 4) = ".xls" Then
                ' 対象のファイルを開く
                Workbooks.Open FilePath
                MsgBox "ファイルを開きました: " & FilePath
                Exit Sub ' マクロを終了
            End If
        End If
    Next i
    
    MsgBox "該当するデータはありませんでした。"
End Sub

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?