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?

ファイルをリネーム&移動&old退避させるマクロ

0
Posted at

背景

  • ファイルを開いたまま、ファイル名や格納先を変更させたい。
  • Webサーバ上のファイルについては標準で実施できるが、ローカルファイルについては開ていると実施できない。(出来るかもだが、私は知らないため、、、)
  • 名前を付けて保存(Ctrl+Shift+S、F12)でファイルのリネームや移動を行えるが、元ファイルが残ってしまう。
  • バックアップのため、元ファイルは「old」ファルダに退避させたい。

機能概要

  1. ファイルダイアログを出力し、リネーム・移動先を入力・選択する。
  2. 入力したファイル名にリネームし、選択した格納先にファイルを移動する。
  3. 元ファイルをoldファイルに移動する。
    (oldフォルダに既に同名ファイルが存在する場合はファイル名末尾に連番を付与する)
'ファイルリネーム(元ファイルold退避)
Public Sub subFileRename()
    Dim wb          As Workbook
    Dim strPathFrom As String
    Dim strPathOld  As String
    Dim strNameFrom As String
    Dim strOld      As String
    On Error GoTo lblEnd

    '初期処理
    Application.DisplayAlerts = False
    Set wb = ActiveWorkbook
    strPathFrom = wb.Path
    strNameFrom = wb.FullName

    '保存先選択(名前を付けて保存(Ctrl+Shift+S、F12)と同等の処理)
    With Application.FileDialog(msoFileDialogSaveAs)
        .InitialFileName = strNameFrom          '初期値:元ファイル
        .AllowMultiSelect = False               '複数選択不可
        If .Show = True Then
            'リネーム&移動
            .Execute
        End If
    End With
    
    '元ファイルをoldファイルに移動(重複する場合、連番付与)
    strPathOld = strPathFrom & "\old"
    strOld = MoveFile(strNameFrom, strPathOld)

lblEnd:
    Application.DisplayAlerts = True

End Sub

補足

  • ロジック中に使用している関数「MoveFile」は、自分で使いやすいように自作したもの。
    このような自作した関数については別途紹介する。
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?