VBA (Visual Basic for Applications) を使用して、指定したフォルダ内のファイル名を全角から半角に変換し、スペースを削除するマクロを作成することができます。VBAでは、`FileDialog`オブジェクトを使用してフォルダを選択することができます。また、ファイル名の全角から半角への変換処理も行います。
以下にVBAのサンプルコードを示します。
### VBAコード
```vba
Option Explicit
' 全角文字を半角に変換する関数
Function ConvertFullWidthToHalfWidth(inputStr As String) As String
Dim outputStr As String
Dim i As Long
Dim ch As String
Dim code As Long
outputStr = ""
For i = 1 To Len(inputStr)
ch = Mid(inputStr, i, 1)
code = AscW(ch)
' 全角英数字と記号の範囲
If code >= &HFF01 And code <= &HFF5E Then
outputStr = outputStr & ChrW(code - &HFF00 + &H20)
ElseIf code = &H3000 Then
outputStr = outputStr & " " ' 全角スペースを半角スペースに変換
Else
outputStr = outputStr & ch
End If
Next i
' スペースを削除
ConvertFullWidthToHalfWidth = Replace(outputStr, " ", "")
End Function
' フォルダ内のファイル名を全角から半角に変換し、スペースを削除してリネームするサブプロシージャ
Sub RenameFilesInFolder()
Dim folderPath As String
Dim fileDialog As FileDialog
Dim fileSystem As Object
Dim folder As Object
Dim file As Object
Dim oldFileName As String
Dim newFileName As String
Dim oldFilePath As String
Dim newFilePath As String
' フォルダ選択ダイアログを表示
Set fileDialog = Application.FileDialog(msoFileDialogFolderPicker)
fileDialog.Title = "処理したいフォルダを選択してください"
If fileDialog.Show = -1 Then
folderPath = fileDialog.SelectedItems(1)
Else
MsgBox "フォルダが選択されませんでした。処理を終了します。"
Exit Sub
End If
' フォルダ内のファイルを処理
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(folderPath)
For Each file In folder.Files
oldFileName = file.Name
newFileName = ConvertFullWidthToHalfWidth(oldFileName)
If oldFileName <> newFileName Then
oldFilePath = folderPath & "\" & oldFileName
newFilePath = folderPath & "\" & newFileName
' ファイルのリネーム
Name oldFilePath As newFilePath
Debug.Print "リネームしました: " & oldFileName & " -> " & newFileName
End If
Next file
MsgBox "処理が完了しました。"
End Sub
```
### 使い方:
1. Excel などのVBAエディタを開きます(`Alt` + `F11` を押す)。
2. 新しいモジュールを挿入し、このコードをコピーして貼り付けます。
3. `Sub RenameFilesInFolder()` を実行すると、フォルダ選択ダイアログが表示されます。
4. 選択したフォルダ内のファイル名が全角から半角に変換され、スペースが削除されます。
### 説明:
- **`ConvertFullWidthToHalfWidth`** 関数では、全角文字を半角に変換し、ファイル名内のスペースを削除します。
- **`Application.FileDialog(msoFileDialogFolderPicker)`** を使用して、フォルダ選択ダイアログを表示します。
- **`Name oldFilePath As newFilePath`** コマンドを使って、ファイルをリネームします。
- **`Debug.Print`** でリネーム結果をイミディエイトウィンドウに出力します。
これで、ExcelやAccessなどのVBA対応アプリケーションを使って、フォルダ内のファイル名を一括で変換してリネームすることができます。