hiko-blog

VBA業務改善

MENU

VBSでフォルダ内のファイル移動

Option Explicit

Dim objFSO, objFolder, objFile, strSourceFolderPath, strDestinationPath

' 引数が渡されているか確認
If WScript.Arguments.Count > 0 Then
    ' ドラッグ&ドロップされたフォルダのパスを取得
    strSourceFolderPath = WScript.Arguments(0)

    ' 移動先のフォルダのパスをユーザーに選択させる
    strDestinationPath = BrowseForFolder()

    ' 移動先のフォルダが選択されたか確認
    If strDestinationPath <> "" Then
        ' FileSystemObjectを作成
        Set objFSO = CreateObject("Scripting.FileSystemObject")

        ' ソースフォルダが存在するか確認
        If objFSO.FolderExists(strSourceFolderPath) Then
            ' ソースフォルダ内のファイルを取得
            Set objFolder = objFSO.GetFolder(strSourceFolderPath)
            For Each objFile In objFolder.Files
                ' FileSystemObjectを使用してファイルを移動
                objFile.Move strDestinationPath & "\" & objFile.Name
            Next

            WScript.Echo "フォルダ内のファイルを移動しました。"
        Else
            WScript.Echo "指定されたフォルダが存在しません。"
        End If

        ' オブジェクトの解放
        Set objFSO = Nothing
        Set objFolder = Nothing
        Set objFile = Nothing
    Else
        WScript.Echo "移動先のフォルダが選択されませんでした。"
    End If
Else
    WScript.Echo "フォルダがドラッグ&ドロップされていません。"
End If

Function BrowseForFolder()
    ' フォルダ選択ダイアログを表示
    Dim objShell, objFolder, strFolderPath

    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.BrowseForFolder(0, "移動先のフォルダを選択してください", 0, 17)

    ' ユーザーがキャンセルを選択した場合は空の文字列を返す
    If Not objFolder Is Nothing Then
        strFolderPath = objFolder.Self.Path
    Else
        strFolderPath = ""
    End If

    Set objFolder = Nothing
    Set objShell = Nothing

    BrowseForFolder = strFolderPath
End Function