6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Excel VBA】Excel2010以降のVBAで画像の実体を挿入する

Last updated at Posted at 2018-10-16

2010以降で記録したマクロで画像貼り付けすると参照扱いに

ブラウザ打鍵系テストをやると待ってる地獄があるじゃないですか。
ほら、キャプチャをひたすらExcelに貼り付けてはマーキングするアレです。
大量のケースがあるともう心が死ぬやつ。あと手動ゆえのミスとかも出ますし。
それはSeleniumでキャプチャ画像を出力して、Excel VBAで予め作ったテンプレートに貼る事で効率化したんですけど、画像をExcelのワークシートに貼り付ける処理をググるよりマクロ記録でやったほうが早いんじゃねって思ったのが間違いだったんです。
2010以降では、マクロの記録で画像を挿入すると、出来上がるコードはリンク貼り付けになっちゃうなんて、そんな。まさか。完全に落とし穴じゃねーか!マクロ記録してなければリンク貼り付けにならんのに!
リンク貼り付けだとパス変わると画像が見えないんですよね…

解決法

前振りはこの辺にしておいて、解決法です。
2007までは有効だった「ActiveSheet.Pictures.Insert」ではなく、「ActiveSheet.Shapes.AddPicture」を使います。

Dim shp as Shape
With Workbook
    ' 画像貼り付け
    With .ActiveSheet
        .Cells(1, 1).Select
        Set shp = .Shapes.AddPicture( _
                fileName:="C:\\temp\img.png", _
                linktofile:=False, _
                savewithdocument:=True, _
                Left:=Selection.Left, _
                Top:=Selection.Top, _
                Width:=0, _
                Height:=0)
    End With

    With shp
        ' 一旦縦横のサイズを100%にリセットする
        .LockAspectRatio = False
        .ScaleHeight 1, msoTrue, msoScaleFromTopLeft
        .ScaleWidth 1, msoTrue, msoScaleFromTopLeft

        ' 縦横比固定で75%に設定
        .LockAspectRatio = True
        .ScaleHeight 0.75, msoTrue, msoScaleFromTopLeft
        ' 最背面に配置
        .ZOrder msoSendToBack
        ' 画像の囲み線を1pxの黒い実線に
        With .Line
            .Visible = msoTrue
            .ForeColor.ObjectThemeColor = msoThemeColorText1
            .ForeColor.TintAndShade = 0
            .ForeColor.Brightness = 0
            .Weight = 1
        End With
    End With
End With
Set shp = Nothing

linktofile:=False, _
savewithdocument:=True, _

ここがキモです!ここでリンク埋め込みか実態埋め込みか、ファイル内に画像を保存するかを設定してます。

なんでわざわざ貼り付けた後に100%にしてるかって、そのままだと100% * 100%になってない時があるんですよ…
縦横比固定にチェックが入ってても73% * 69%みたいなわけわからん数値になってたりするので…

6
9
4

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
6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?