項目

フォルダを操作する(FileSystemObject)

概要

FileSystemObjectを使用してフォルダの作成、移動、コピー、削除を行います。

Option Compare Database
Option Explicit

'--------------------------------------------------------
' 名称    : operateFolder
'
' 機能    : フォルダ操作
'
' 参照設定: Microsoft Scripting Runtime
'
'--------------------------------------------------------
Sub operateFolder()

    Dim fso      As New FileSystemObject
    Dim fldr     As Folder
    
    Dim movePath As String
    Dim copyPath As String
    Dim fldrPath As String
    
    fldrPath = "d:\temp\test"
    movePath = "d:\temp\move\test"
    copyPath = "d:\temp\copy"
    
On Error GoTo err_handle
    
    'フォルダあり?
    If Not fso.FolderExists(fldrPath) Then
        'フォルダの作成
        Set fldr = fso.CreateFolder(fldrPath)
    Else
        'フォルダの取得
        Set fldr = fso.GetFolder(fldrPath)
    End If
    
    If fldr Is Nothing Then
        Debug.Print "ないよ!!"
        GoTo exit_handle
    End If
        
    'フォルダあり?
    If Not fso.FolderExists(movePath) Then
        'フォルダの移動
        fldr.Move movePath
    End If
    
    'フォルダのコピー(上書き)
    fldr.Copy copyPath, True
    
    'フォルダあり?
    If fso.FolderExists(movePath) Then
        'フォルダの削除
        fldr.Delete
    End If
    
exit_handle:
    Set fso = Nothing
    Set fldr = Nothing
    Exit Sub
err_handle:
    Debug.Print Err.Description
    Resume exit_handle
End Sub