【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
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-

[VBA]InStr文字列確認 【VBA】指定の文字列が含まれているか & 前後の文字列を返す|InStr/InStrRev -

[VBA]開いていたら閉じる 【VBA】指定のブックが開いていたら閉じる -

[VBA]Cutbefore after 【VBA】文字列から指定文字より前/後ろをカットする|InStrRev/Left$/Mid$ -

[VBA]Dirで存在確認 【VBA】フォルダとファイルの存在確認|FSOよりもDir -

[VBA]fsoSingleton pattern 【VBA】FSO(“Scripting.FileSystemObject”)|シングルトン化して使う -

[VBA]Reset filtersand outlines 【VBA】オートフィルタ解除&非表示を表示する|.FilterMode/.Outline