この記事では、Excel VBAを用いて画像ファイルの解像度をファイル名に反映する方法を詳しく紹介します。具体的なコードとその解説、さらには応用例を含めて、より実用的な知識の習得を目指します。
目次
基本的な処理: 画像ファイルの解像度をファイル名に反映
Sub RenameImageWithResolution()
Dim filePath As String
Dim img As Picture
Dim newFileName As String
Dim resolution As String
filePath = "C:\path_to_image.jpg" '画像ファイルのパス
Set img = ThisWorkbook.Pictures.Insert(filePath)
resolution = img.Width & "x" & img.Height
newFileName = Replace(filePath, ".jpg", "_" & resolution & ".jpg")
Name filePath As newFileName
img.Delete
End Sub
コードの詳細解説
このコードは、指定した画像ファイルの解像度を取得して、その情報をファイル名に反映させるVBAのマクロです。
1. **filePath**で画像ファイルのパスを指定します。
2. **img**として、指定した画像をExcelにインポートします。
3. **resolution**で画像の横と縦の解像度を取得し、”x”で結合します。
4. **newFileName**で、元のファイル名から拡張子を除去し、解像度を追加して新しいファイル名を作成します。
5. 最後に、**Name**関数でファイル名を変更し、Excel上の画像を削除します。
応用例
応用例1: フォルダ内の全ての画像をリネーム
Sub RenameAllImagesInFolder()
Dim folderPath As String
Dim fileName As String
Dim img As Picture
Dim newFileName As String
Dim resolution As String
folderPath = "C:\path_to_folder\" '画像が保存されているフォルダのパス
fileName = Dir(folderPath & "*.jpg")
Do While fileName <> ""
Set img = ThisWorkbook.Pictures.Insert(folderPath & fileName)
resolution = img.Width & "x" & img.Height
newFileName = Replace(fileName, ".jpg", "_" & resolution & ".jpg")
Name folderPath & fileName As folderPath & newFileName
img.Delete
fileName = Dir()
Loop
End Sub
応用例2: 他の画像形式にも適用
Sub RenameAllImagesIncludingPNGs()
'...(前述のコードと同様の部分は省略)...
fileName = Dir(folderPath & "*.*") '全てのファイルを対象とする
Do While fileName <> ""
If Right(fileName, 4) = ".jpg" Or Right(fileName, 4) = ".png" Then
'...(前述のコードと同様の処理)...
End If
fileName = Dir()
Loop
End Sub
応用例3: 解像度が一定以上の画像のみリネーム
Sub RenameHighResolutionImagesOnly()
'...(前述のコードと同様の部分は省略)...
Do While fileName <> ""
Set img = ThisWorkbook.Pictures.Insert(folderPath & fileName)
If img.Width > 1920 And img.Height > 1080 Then '1920x1080以上の画像のみ対象とする
'...(前述のコードと同様の処理)...
End If
img.Delete
fileName = Dir()
Loop
End Sub
まとめ
Excel VBAを使用して、画像ファイルの解像度をファイル名に反映させる方法を学びました。基本的な手法から、フォルダ内の複数の画像を一括で処理する方法、特定の解像度以上の画像だけを対象とする方法など、応用的な手法までを網羅しました。これらの知識を活用し、日常業務や自動化タスクの中で最大限に活用してください。
コメント