【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]CreateObjectまとめ 【VBA】CreateObject|dictionary・テキストファイル・outlook・Access用にオブジェクトを生成する -
文字列から拡張子を取得する 【VBA】文字列から拡張子を取得して、文字列として返す|InStrRev -
[VBA]開いているブックからファイルを探す 【VBA】開いている全ブックから対象ブックをセット|InStr ファイル名の一部で判定 -
[VBA]日付を文字列に 【VBA】日付型を文字列にする|Format -
クラスでForEachを使いたい 【VBA】クラスで通常のCollection機能を利用する準備|ForEachが使えない -
[VBA]copyfile 【VBA】ブックを複製する|fso.CopyFile