銀河鉄道

【VBA】パスからfsoオブジェクトを取得する|fso.GetFolder/.GetFile

サムネイル
[VBA]get fso objectfrom path

フォルダパスから、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 FolderExists
before getting object.

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧