【VBA】パスからfsoオブジェクトを取得する|fso.GetFolder/.GetFile
作成日:2022-11-04
更新日:2025-10-05

フォルダパスから、fsoをセットしてオブジェクトを返す
' Get folder object from path using FileSystemObject
' FileSystemObjectを使ってフォルダオブジェクトを取得する
Public Function GetFolderFSO(ByVal folderPath As String) As Object
    On Error GoTo ErrHandler
    
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    If fso.FolderExists(folderPath) Then
        Set GetFolderFSO = fso.GetFolder(folderPath)
    Else
        Set GetFolderFSO = Nothing
    End If
    Exit Function
    
ErrHandler:
    Set GetFolderFSO = Nothing
End Functionファイルパスから、fsoをセットしてオブジェクトを返す
' Get file object from path using FileSystemObject
' FileSystemObjectを使ってファイルオブジェクトを取得する
Public Function GetFileFSO(ByVal filePath As String) As Object
    On Error GoTo ErrHandler
    
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    If fso.FileExists(filePath) Then
        Set GetFileFSO = fso.GetFile(filePath)
    Else
        Set GetFileFSO = Nothing
    End If
    Exit Function
    
ErrHandler:
    Set GetFileFSO = Nothing
End Function必ず FolderExists を確認する
Example Usage|使用例
Sub TestGetFolderFSO()
    Dim folder As Object
    Set folder = GetFolderFSO("C:\Users\Usagi\Documents")
    
    If Not folder Is Nothing Then
        Debug.Print "Folder name: "; folder.Name
    Else
        Debug.Print "Folder not found."
    End If
End Sub
Sub TestGetFileFSO()
    Dim f As Object
    Set f = GetFileFSO("C:\Users\Usagi\Documents\Report.xlsx")
    
    If Not f Is Nothing Then
        Debug.Print "File name: "; f.Name
        Debug.Print "File size: "; f.Size & " bytes"
        Debug.Print "Created: "; f.DateCreated
    Else
        Debug.Print "File not found."
    End If
End Sub

FSOはシングルトンで使おう
| GetFolder|フォルダオブジェクトを取得 |
| FolderExists|フォルダが存在するか確認 |
| Return Value|戻り値 |
| Nothing|オブジェクトが未設定 |
| Error Handling|エラーハンドリング |
Always check 
before getting object.
FolderExists before getting object.
      
    
2022-11-04
      編集後記:
      この記事の内容がベストではないかもしれません。
    
記事一覧
- 
          
            
      
      

クラスでForEachを使いたい 【VBA】クラスで通常のCollection機能を利用する準備|ForEachが使えない - 
          
            
      
      

[VBA]Redim とRedim Preserve 【VBA】配列の要素数を決める|ReDim vs ReDim Preserve & Pythonとの違い - 
          
            
      
      

Excelテーブル最終行に値を追加 【VBA】Excelのテーブルの最終行に値を追加する - 
          
            
      
      

テーブルの指定位置に行を追加 【VBA】Excelテーブルの指定した位置に行を追加する - 
          
            
      
      

[VBA]Run PowerShellfrom VBA 【VBA】指定場所にあるPowerShellスクリプトを実行する - 
          
            
      
      

VBAでテーブル設定 【VBA】Excelにテーブルを設定する