■■■■■■■第4章 16■■■■■■■

■■■■p175プロンプト例

あなたは優秀なExcel VBAのプログラマーです。 
次の操作をするExcel VBAのプログラムを書いてください。

＃＃前提条件
・「ファイル名変更」シートに以下の情報がある
　　B1セル：対象フォルダーのパス
　　A3セル以下：対象フォルダー内にあるファイル名の一覧

＃＃やりたいこと
・対象フォルダー内のファイルの名前を変更する
・A3セル以下のファイル名を、それぞれB3セル以下の文字列に変更する
・マクロ名は「ファイル名の一括変更」とする


■■■■p176コード例

Sub ファイル名の一括変更()
    Dim ws As Worksheet
    Dim folderPath As String
    Dim i As Long
    Dim oldName As String, newName As String
    Dim oldFullPath As String, newFullPath As String
    
    ' 対象シートを設定
    Set ws = ThisWorkbook.Sheets("ファイル名変更")
    
    ' B1セルからフォルダパスを取得
    folderPath = ws.Range("B1").Value
    If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
    
    ' A3セルから下のファイル名を順に処理
    i = 3
    Do While ws.Cells(i, 1).Value <> ""
        oldName = ws.Cells(i, 1).Value
        newName = ws.Cells(i, 2).Value
        
        ' ファイル名が空の場合はスキップ
        If newName <> "" Then
            oldFullPath = folderPath & oldName
            newFullPath = folderPath & newName
            
            ' ファイルが存在する場合のみ名前変更
            If Dir(oldFullPath) <> "" Then
                Name oldFullPath As newFullPath
            Else
                MsgBox "ファイルが見つかりません: " & oldName, vbExclamation
            End If
        End If
        i = i + 1
    Loop
    
    MsgBox "ファイル名の変更が完了しました。", vbInformation
End Sub
