【VBA】ブックを複製する|fso.CopyFile
作成日:2022-12-02
更新日:2025-10-05

ブックを複製し、指定のフルパスへ保存する
'-----------------------------------------
' Copy file with overwrite option and error handling
' ファイルコピー(上書き許可オプション付き・エラーハンドリング)
'-----------------------------------------
Public Function CopyBook( _
ByVal srcPath As String, _
ByVal dstPath As String, _
Optional ByVal overwrite As Boolean = False) As Boolean
On Error GoTo ErrHandler
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(srcPath) Then Exit Function
If fso.FileExists(dstPath) Then
If Not overwrite Then Exit Function
fso.DeleteFile dstPath, True
End If
fso.CopyFile srcPath, dstPath, True
CopyBook = True
Exit Function
ErrHandler:
CopyBook = False
End Function
- 存在確認|FileExistsで保証
- overwrite指定|上書きするかどうかを選ぶ
- 戻り値 Boolean|成功/失敗を呼び出し側で判定する
Example usage | 使用例
If Not CopyBook("C:\tmp\src.xlsx", "C:\tmp\dst.xlsx", True) Then
MsgBox "コピーに失敗しました"
End If

FSOはシングルトンで使おう
Referenced Insights & Citations
- Microsoft Docs: FileCopy statement
- Microsoft Docs: FileSystemObject.CopyFile method
| FileCopy|ファイルコピー |
| Overwrite|上書き |
| Error Handling|エラーハンドリング |
| FileSystemObject|ファイルシステムオブジェクト |
| Boolean Return|真偽値戻り値 |
Always control overwrite
and error handling
when copying files.
and error handling
when copying files.
2022-12-02
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-
[VBA]Nameでパス変更 【VBA】ブックのフルパスを変更する(ファイル名の変更も含む)|Name -
vbaの色設定 【VBA】色の定数は8つ|RGB対称表 -
[VBA]CreateObjectまとめ 【VBA】CreateObject|dictionary・テキストファイル・outlook・Access用にオブジェクトを生成する -
グラフ設定を変更する 【VBA】グラフ設定を動的に変更する -
[VBA]buttonに何が登録されてるか 【VBA】ボタンに登録されているマクロ名を調べたい -
UsedRangeのデータを配列で取得 【VBA】シートにあるデータを配列に格納する(空白含む)|UsedRange