【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]Transpose2D Array 【VBA】配列の縦横変換|WorksheetFunction.Transpose は使わない -

ユーザーフォームのタイトルバー非表示 【VBA】ユーザーフォームのタイトルバーを非表示にしてシステムっぽい見た目にする -

[VBA]Killthe progress dialog VBA|保存処理(SaveAs)がフリーズする原因と対策 -

[VBA]Merge1D Arrays 【VBA】一次元配列と一次元配列を結合する -

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

[VBA]開いているブックからファイルを探す 【VBA】開いている全ブックから対象ブックをセット|InStr ファイル名の一部で判定