0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VBAでファイルを移動させるプログラム

Last updated at Posted at 2025-03-18

まずは全体像から

Sub MoveFile()
    Dim sourcePath As String
    Dim destPath As String
    Dim fileName As String
    Dim fullDestPath As String
    Dim userResponse As VbMsgBoxResult
    
    ' 移動するファイルのフルパス
    sourcePath = "C:\Users\User\Desktop\source\test.xlsx"
    
    ' 移動先のフォルダ(末尾に \ をつける)
    destPath = "C:\Users\User\Desktop\destination\"
    
    ' ファイル名を取得
    fileName = Dir(sourcePath)
    
    ' 移動先のフルパス
    fullDestPath = destPath & fileName
    
    ' ファイルが存在するか確認
    If fileName <> "" Then
        ' 移動先に同名のファイルが存在する場合の処理
        If Dir(fullDestPath) <> "" Then
            ' 上書きするかどうかをユーザーに確認
            userResponse = MsgBox("移動先に同じファイルがあります。上書きしますか?", vbYesNo, "確認")
            
            ' 「いいえ」を選択した場合、処理を終了
            If userResponse = vbNo Then
                MsgBox "処理を中止します。", vbInformation, "キャンセル"
                Exit Sub
            End If
        End If
        
        ' ファイルをコピペ(上書き含む)
        FileCopy sourcePath, fullDestPath
        
        ' 元のファイルを削除
        Kill sourcePath
        
        MsgBox "ファイルを上書き移動しました: " & fullDestPath, vbInformation, "完了"
    
    Else
        MsgBox "ファイルが見つかりません: " & sourcePath, vbCritical, "エラー"
    End If
    
End Sub

解説

指定したExcelファイルを別フォルダに移動するが、もし移動先に同じ名前のファイルがある場合、ユーザーに上書きするかを確認して回答に合わせて処理を切り分ける。

コードの流れ

1 移動元ファイルの存在を確認
2 移動先に同じファイルがあるかチェック
  ● ある場合 → ユーザーに「上書きしますか?」と確認
   ● 「はい」 → 上書き移動
   ● 「いいえ」 → 終了
  ● ない場合 → そのまま移動
3 FileCopy でファイルをコピーし、元のファイルを Kill で削除
4 完了メッセージを表示
5 エラー処理(移動元ファイルがない場合はメッセージ表示)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?