VBAでは、ファイルの名前変更(リネーム)や移動を自動で行うことができます。 実はこの2つは、同じ仕組みで実現できるのがポイントです。
ファイル名変更と移動の違い
| 操作 | 内容 |
|---|---|
| ファイル名変更 | 同じフォルダ内で名前を変える |
| ファイル移動 | 別フォルダへ移動する |
VBAではどちらも次の1行で実現できます。
Name 元のパス As 新しいパス
目次
1. Nameステートメントで変更・移動する(最もシンプル)
基本構文
Name 元のパス As 新しいパス
ファイル名の変更(リネーム)
Sub RenameFile()
Name "C:\Sample\test.txt" As "C:\Sample\test_new.txt"
End Sub
→ test.txt → test_new.txt に変更されます。
ファイルの移動
Sub MoveFile()
Name "C:\Sample\test.txt" As "C:\Backup\test.txt"
End Sub
→ Sample → Backup に移動されます(元のファイルには残らない)。
変数を使う実務向け例
Sub RenameFile()
Dim sourcePath As String
Dim destPath As String
sourcePath = "C:\Sample\test.txt"
destPath = "C:\Sample\test_new.txt"
Name sourcePath As destPath
End Sub
Nameステートメントの注意点
① 移動先フォルダが存在しないとエラー
→ 事前にフォルダ作成が必要
② 同名ファイルが存在するとエラー
→ 上書き不可(FileCopy と違い自動上書きしない)
③ ワイルドカードは使えない
Name "C:\Sample\*.txt" As ...
→ 不可
2. FileSystemObjectで変更・移動する(可読性・拡張性が高い)
FileSystemObject(FSO) を使うと、より柔軟にファイル操作ができます。
ファイル名変更(リネーム)
Sub RenameFile()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
fso.GetFile("C:\Sample\test.txt").Name = "test_new.txt"
End Sub
ファイル移動
Sub MoveFile()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile "C:\Sample\test.txt", "C:\Backup\test.txt"
End Sub
FileSystemObjectのメリット
- 移動専用メソッドがある(MoveFile)
- コードの可読性が高い
- ファイル操作を統一管理できる(コピー・削除・存在確認など)
3. Name と FileSystemObject の違い
| 項目 | Name | FileSystemObject |
|---|---|---|
| 記述量 | 少ない | やや多い |
| 上書き | × | ×(MoveFileも同様) |
| 可読性 | ○ | ◎ |
| ワイルドカード | × | ○(MoveFileは可) |
| 実務利用 | シンプル処理 | 複雑処理・統一管理 |
4. 実務でよく使うパターン
日付付きファイル名に変更
Sub RenameWithDate()
Dim sourcePath As String
Dim destPath As String
sourcePath = "C:\Report\report.xlsx"
destPath = "C:\Report\report_" & Format(Now, "yyyymmdd") & ".xlsx"
Name sourcePath As destPath
End Sub
安全に使う実務コード(存在確認付き)
Sub SafeMoveFile()
Dim sourcePath As String
Dim destPath As String
sourcePath = "C:\Sample\test.txt"
destPath = "C:\Backup\test.txt"
'存在確認
If Dir(sourcePath) = "" Then
MsgBox "ファイルが存在しません"
Exit Sub
End If
'移動
Name sourcePath As destPath
End Sub
5. まとめ
VBAでファイル名変更・移動を行う方法は次の2つです。
| 方法 | 用途 |
|---|---|
| Name | シンプルな変更・移動 |
| FileSystemObject | 可読性・拡張性重視 |
使い分けは以下の通り。
- 簡単に変更・移動 → Name
- 管理しながら処理 → FileSystemObject
コメント