異なるサイズの画像データをExcelマクロで統一する
-
rootipで商標案件を検索した後、Excelでエクスポートすると画像サイズがバラバラになり、書式調整に時間がかかります。何か良い方法はありませんか。
-
Excel出力後、VBA(マクロ)を活用することで、画像データのサイズを一括で統一し、縦横比を維持したままセル内に収めることができます。
貴社内のセキュリティポリシーをご確認のうえ、マクロの利用が許可されている場合は、以下の手順で設定・実行をお試しください。
【操作手順】
①調整したいExcelデータを開き、代表図の列の横幅を希望の横幅に調整します。
②「名前を付けて保存」でファイル形式を Excel マクロ有効ブック(.xlsm) として保存します。
③保存したマクロブックを開き、[Alt]+[F11] を押してVBAエディタを起動します。
④メニューバーから[挿入] → [標準モジュール] をクリックします。
⑤以下のコードを貼り付け、上書き保存します。
—–ココカラ——
Option Explicit
Sub FitPicturesToCells_KeepAspect_Center_Simple()
Dim shp As Shape
Dim rngBox As Range
Dim boxW As Double, boxH As Double
Dim ow As Double, oh As Double
Dim scaleValue As Double
Dim scaleW As Double, scaleH As DoubleOn Error Resume Next For Each shp In ActiveSheet.Shapes If shp.Type = msoPicture Or shp.Type = msoLinkedPicture Then Set rngBox = shp.TopLeftCell boxW = rngBox.Width boxH = rngBox.Height ow = shp.Width oh = shp.Height If ow <= 0 Or oh <= 0 Or boxW <= 0 Or boxH <= 0 Then GoTo ContinueNext shp.LockAspectRatio = msoTrue scaleW = boxW / ow scaleH = boxH / oh If scaleW < scaleH Then scaleValue = scaleW Else scaleValue = scaleH End If If scaleValue <= 0 Then GoTo ContinueNext shp.Width = ow * scaleValue shp.Height = oh * scaleValue shp.Left = rngBox.Left + (boxW - shp.Width) / 2 shp.Top = rngBox.Top + (boxH - shp.Height) / 2 End IfContinueNext:
Next shpOn Error GoTo 0 MsgBox "縦横比を維持して、全画像をセル内中央に配置しました。"End Sub
—–ココマデ——
⑥左上のエクセルアイコンをクリック(またはダイアログ右上の「×」でVBAエディタを閉じる)し、Excelに戻ります。
⑦[Alt]+[F8]をクリックし、 FitPicturesToCells_KeepAspect_Center_Simple を選択し、[実行] をクリックします。
【補足】
・本マクロは、画像の縦横比を維持しながら、画像をセル内に収めて中央寄せします。
・結合セルを使用している場合は、動作が想定と異なる可能性があります。
・マクロ実行前に、セルサイズを整えておくとよりきれいに配置されます(手順①)。

