カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

Excel VBA 画像の挿入

この記事は最終更新日から1年以上経過しています。
Sub auto_open()

    Dim myFileName As String
    Dim myShape As Shape

    myFileName = ActiveWorkbook.Path & "\sample.bmp"

    ' 選択位置に画像ファイルを挿入し、変数myShapeに格納
    Set myShape = ActiveSheet.Shapes.AddPicture( _
          Filename:=myFileName, _
          LinkToFile:=False, _
          SaveWithDocument:=True, _
          Left:=Selection.Left, _
          Top:=Selection.Top, _
          Width:=0, _
          Height:=0)

    ' 挿入した画像に対して元画像と同じ高さ・幅にする
    With myShape
        .ScaleHeight 1, msoTrue
        .ScaleWidth 1, msoTrue
    End With

End Sub

ACCESSからExcelを操作し、挿入する場合

Dim xlApp   As Object
Dim xlBook  As Object
Dim xlSheet As Object

Dim FileName   As String
Dim myFileName As String
Dim myShape    As Object

FileName = Environ("USERPROFILE") & "\デスクトップ\sample.xls"

Set xlApp   = CreateObject("Excel.Application")
Set xlBook  = xlApp.Workbooks.Add
Set xlSheet = xlBook.WorkSheets(1)

With xlSheet

    myFileName = Environ("USERPROFILE") & "\デスクトップ\sample.bmp"

    .Range("A1").Select
    .Pictures.Insert(myFileName).Select

End With

'保存
xlBook.Saveas (FileName)

xlBook.Close

xlApp.Application.Quit

Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
この記事がお役に立ちましたらシェアお願いします
11,826 views

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です