【VBA】Insert image file

Yu can insert image file.

PR

VBA Code

As an example, Insert “sample.jpg” in “sample” sheet.

image file
image file
Option Explicit

Sub sample()
    
    Dim filePath As String
    Dim ws As Worksheet
    Dim topPosition As Double
    Dim leftPosition As Double
    Dim shapeObj As Shape
    
    'Set "image file path"
    filePath = "C:\Users\user\Desktop\sample.jpg"

    Set ws = Worksheets("sample")
    
    'Get the cells position to insert  image file
    With ws.Range("B2")
        topPosition = .Top
        leftPosition = .Left
    End With
    
    'Get insert image
    Set shapeObj = ws.Shapes.AddPicture( _
        Filename:=filePath, _
        LinkToFile:=msoTrue, _
        SaveWithDocument:=msoTrue, _
        Top:=topPosition, _
        Left:=leftPosition, _
        Width:=0, _
        Height:=0 _
    )
    
    'Insert image
    With shapeObj
        .ScaleHeight 1, msoTrue
        .ScaleWidth 1, msoTrue
    End With

End Sub

Set “image file path“(Line 12).

PR

Result

You inserted image file!

Result
Result
PR

FYI

For more information about following, see the following official online manual:

Shapes property” of “Worksheet Object”


AddPicture method” of “Shapes Object”


ScaleHeight method” of “Shape Object”


ScaleWidth method” of “Shape Object”

タイトルとURLをコピーしました