1) Please run the following code in the Excel Application.
Sub Macro1()
'Delete all shapes if exists
For i = ActiveSheet.Shapes.Count To 1 Step -1
ActiveSheet.Shapes(i).Delete
Next i
'Add a Rectangle
With ActiveSheet.Shapes.AddShape(Type:=msoShapeRectangle, Left:=20, Top:=20, Width:=200, Height:=120)
.Name = "myRectangle"
End With
'Make some formatting to the myRectangle
With ActiveSheet.Shapes("myRectangle")
.Line.Visible = msoTrue
.Line.ForeColor.RGB = vbBlue
.Line.Weight = 5
.Fill.UserPicture "https://upload.wikimedia.org/wikipedia/en/b/ba/Flag_of_Germany.svg"
End With
End Sub
2) Please check if you got the following Rectangle in your Excel Sheet.
3) I am looking for a macro which gives me the following picture.
As you can understand that I want to make some margins between borders and flag.
Pls try .PictureFormat.Crop
to get your expected output.
Microsoft documentation:
Sub Macro1()
Dim i
'Delete all shapes if exists
For i = ActiveSheet.Shapes.Count To 1 Step -1
ActiveSheet.Shapes(i).Delete
Next i
'Add a Rectangle
With ActiveSheet.Shapes.AddShape(Type:=msoShapeRectangle, Left:=20, Top:=20, Width:=200, Height:=120)
.Name = "myRectangle"
End With
'Make some formatting to the myRectangle
With ActiveSheet.Shapes("myRectangle")
.Line.Visible = msoTrue
.Line.ForeColor.RGB = vbBlue
.Line.Weight = 5
.Fill.UserPicture "https://upload.wikimedia.org/wikipedia/en/b/ba/Flag_of_Germany.svg"
With .PictureFormat.Crop
Dim iW: iW = .PictureWidth
Dim iH: iH = .PictureHeight
Const OFFSET_PCT = 0.05 ' Modify as needed
.PictureWidth = iW * (1 - 2 * OFFSET_PCT)
.PictureHeight = iH * (1 - 2 * OFFSET_PCT * iW / iH)
End With
End With
End Sub