Home > 即効テクニック > Excel VBA > ファイル操作関連のテクニック > 特定フォルダ内のブックから1つのブックをランダムに開く

即効テクニック

ファイル操作関連のテクニック

特定フォルダ内のブックから1つのブックをランダムに開く

(Excel 97/2000)
サンプルマクロは、C:\内のブックから1つのブックをランダムに抽出して開きます。

Sub Sample()

    'ファイルの存在するフォルダ
    Const myDir As String = "C:\"
    
    Dim myFileName() As String
    Dim myCnt As Long, i As Long
    
    myCnt = 1
    ReDim myFileName(1 To 1) As String
    myFileName(1) = Dir(myDir & "*.xls")
    
    While myFileName(myCnt) <> vbNullString
        myCnt = myCnt + 1
        ReDim Preserve myFileName(1 To myCnt)
        myFileName(myCnt) = Dir()
    Wend
    If myFileName(1) = vbNullString Then Exit Sub
    
    Randomize
    i = Int(Rnd * (myCnt - 1)) + 1
    Application.DisplayAlerts = False
    Workbooks.Open myDir & myFileName(i)
    Application.DisplayAlerts = True

End Sub