VBA Excel automatic image resize & border - excel

I would like to have my image properly resized and bordered with the black line, thickness 1.
My situation looks like this:
and when I used this code:
Sub ResizeCivilsA()
SizeToRange Sheets("Civils 1").Pictures("Picture 29"), Range("B3:L46")
End Sub
Function SizeToRange(s, Target As Range)
s.Left = Target.Left + 10
s.Top = Target.Top - 5
s.Width = Target.Width
s.Height = Target.Height
End Function
, everything was adjusted fine, but:
It have been done only for the specified shape id, which is "Picture 29"
It was without the borders
So I tried then:
Sub ResizeCivilsA()
Dim shp As Shape
For Each shp In ThisWorkbook.Worksheets
If shp.Name Like "*Picture*" Then
SizeToRange shp, Range("B3:L46")
End If
Next
and finally I am getting error:
Type mismatch, with debugger pointing the line:
For Each shp In ThisWorkbook.Worksheets
Regarding the border around the image I found the common solution here:
https://learn.microsoft.com/en-us/office/vba/api/Excel.Range.BorderAround
However after appliance into my work:
Worksheets("Civils 1").Shape("Picture 29").BorderAround _
ColorIndex:=3, Weight:=xlThick
it wasn't enough since I had to remove the _ and got nothing afterward.
Is there some way to have the possibility for instant resizing the image and making the border around it for ANY attached image, which as default is called "Picture..."?

Try this code.
Read code's comments and adjust it to fit your needs
EDIT: The code checks if picture is within target range ad then adjusts its properties.
Code:
Option Explicit
Public Sub ResizeAllShapesInSheet()
Dim targetSheet As Worksheet
Dim targetRange As Range
Dim targetShape As Shape
' Define the sheet that has the pictures
Set targetSheet = ThisWorkbook.Worksheets("Civils 1")
' Define the range the images is going to fit
Set targetRange = targetSheet.Range("B3:L46")
' Loop through each Shape in Sheet
For Each targetShape In targetSheet.Shapes
' Check "picture" word in name
If targetShape.Name Like "*Picture*" Then
' Call the resize function
SizeToRange targetShape, targetRange
End If
Next targetShape
End Sub
Private Sub SizeToRange(ByVal targetShape As Shape, ByVal Target As Range)
If Not (targetShape.Left >= Target.Left And _
targetShape.Top >= Target.Top And _
targetShape.Left + targetShape.Width <= Target.Left + Target.Width And _
targetShape.Top + targetShape.Height <= Target.Top + Target.Height) Then Exit Sub
' Adjust picture properties
With targetShape
' Check if next line is required...
.LockAspectRatio = msoFalse
.Left = Target.Left + 10
.Top = Target.Top - 5
.Width = Target.Width
.Height = Target.Height
End With
' Adjust picture border properties
With targetShape.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 0, 0)
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = 0
.Transparency = 0
.Visible = msoTrue
.Weight = 6
End With
End Sub
Let me know if it works

Initial read looks like your For Each is looking for Shape objects, but you are giving it a collection of Sheet objects.
For Each sht In ThisWorkbook.Worksheets
For Each shp In sht.Shapes
If shp.Name Like "*Picture*" Then
Set r1 = shp.TopLeftCell
Set r2 = r1.Offset(10, 43)
SizeToRange shp, Range(r1.Address & ":" & r2.Address)
End If
Next shp
Next sht
Hope that helps!
EDIT: Updated with relative address.

Related

How to insert a picture from an existing table with file path and desired placement

I'm trying to create the following template:
The user creates a table in a "Data Entry" worksheet that lists the following:
File path ie: P:\Phone Camera Dump\20121224_111617.jpg
Range where the picture is to be placed in the "PICS" worksheet.
Once the list is finalized, the user executes and images are placed within the ranges specified on the "PICS" worksheet and dynamically re-sized.
Presently the range has a set width of 624px and a height of 374px, but ideally, I would like the image to resize (aspect ratio not locked) dynamically in the width and height change.
I've used the following code as a base but am struggling with how to incorporate the cell ranges instead of the static row updates:
Sub InsertSeveralImages()
Dim pic_Path As String 'File path of the picture
Dim cl As Range, Rng As Range
Dim WS_Templte As Worksheet
Set WS_Templte = Worksheets("PICS")
Set Rng = Worksheets("Data Entry").Range("C13:C42")
pastingRow = 2
For Each cl In Rng
pic_Path = cl.Value
Set InsertingPicture = WS_Templte.Pictures.Insert(pic_Path)
'Setting of the picture
With InsertingPicture
.ShapeRange.LockAspectRatio = msoTrue
.Height = 100
.Top = WS_Templte.Rows(pastingRow).Top
.Left = WS_Templte.Columns(3).Left
End With
pastingRow = pastingRow + 5
Next cl
Set myPicture = Nothing
WS_Templte.Activate
End Sub
Any thoughts?
I figured it out. Here is the code in case anyone wants to use it:
Public Sub InsertPictures()
Dim vntFilePath As Variant
Dim rngFilePath As Range
Dim vntPastePath As Variant
Dim rngPastePath As Range
Dim lngCounter As Long
Dim pic As Picture
Set WS_Templte = Worksheets("PICS")
On Error GoTo ErrHandler
With ThisWorkbook.Sheets("PICS") '<-- Change sheet name accordingly
' Set first cell containing a row number
Set rngFilePath = .Range("BJ7")
vntFilePath = rngFilePath.Value
' Set first cell containing a paste range
Set rngPastePath = .Range("BK7")
vntPastePath = rngPastePath.Value
Do Until IsEmpty(vntFilePath)
If Dir(vntFilePath) = "" Then vntFilePath = strNOT_FOUND_PATH
Set pic = .Pictures.Insert(vntFilePath)
lngCounter = lngCounter + 1
With pic
.ShapeRange.LockAspectRatio = msoFalse
If .ShapeRange.Rotation = 90! Or .ShapeRange.Rotation = 270! Then
.Height = Application.CentimetersToPoints(16.3)
.Width = Application.CentimetersToPoints(10.03)
.Top = WS_Templte.Rows(rngPastePath).Top - (.Height - .Width) / 2#
.Left = WS_Templte.Columns(4).Left + (.Height - .Width) / 2#
Else
.Width = Application.CentimetersToPoints(10.03)
.Height = Application.CentimetersToPoints(16.3)
.Top = WS_Templte.Rows(rngPastePath).Top
.Left = WS_Templte.Columns(4).Left
End If
End With
Set rngFilePath = rngFilePath.Offset(1)
vntFilePath = rngFilePath.Value
Set rngPastePath = rngPastePath.Offset(1)
vntPastePath = rngPastePath.Value
Loop
End With
MsgBox lngCounter & " pictures were inserted.", vbInformation
ExitProc:
Set rngFilePath = Nothing
Set pic = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitProc
End Sub

How to add images to the cells in excel vba

I want to add an image to Cell B1,
and then put the same images to B15, B29, B43, ......B57 (which are increasing by 14) at once
I searched for the ways to do this, but couldn't find how to.
Could someone please tell me how to do this?
Option 1 based on this solution
Option Explicit
Sub TiragePictures()
Const PicPath = "c:\PPP\AAA.png" ' your own path to the image
Dim ws As Worksheet, r As Long, cell As Range
Set ws = ActiveSheet
For r = 15 To 57 Step 14
Set cell = ws.Cells(r, "B")
With ws.Pictures.Insert(PicPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 70
.Height = 50
End With
.Left = cell.Left
.Top = cell.Top
.Placement = 1
.PrintObject = True
End With
Next
End Sub
Option2 with Shapes.AddPicture method
Sub TiragePictures2()
Const PicPath = "c:\PPP\AAA.png" ' your own path to the image
Dim ws As Worksheet, r As Long, cell As Range, sh As Shape
Set ws = ActiveSheet
For r = 15 To 57 Step 14
Set cell = ws.Cells(r, "B")
With ws.Shapes.AddPicture(Filename:=PicPath, LinkToFile:=False, _
SaveWithDocument:=True, Left:=cell.Left, _
Top:=cell.Top, Width:=-1, Height:=-1) '-1 retains the width/height of the existing file
.LockAspectRatio = True 'before resizing, set the proportions to keep
.Width = 70
.Height = 50
End With
Next
End Sub

Importing multiple images using filepath based on Cell Value

I want to import multiple images based on filepath present in a "C" column. Jpeg Files are in a folder name "FolderOf_Images" and Upon running the code it does nothing and also no error was thrown. Surprisingly it worked only once and all pictures were imported in "D" column.
Image files will be placed in D Column. The source code I have tried is below without success.
Google driver Excel File Link
Sub InsertPicsIntoExcel()
'Pictures saved with file
'Set column width (ie, pic width) before running macro
Application.ScreenUpdating = False
Dim r As Range, Shrink As Long
Dim shp As Shape
Shrink = 0 'Provides negative offset from cell borders when > 0
On Error Resume Next
''''Delete existing shapes/pictures
For Each shp In ActiveSheet.Shapes
shp.Delete
Next shp
ActiveSheet.Rows.AutoFit
''''Insert shapes/pictures
For Each r In Range("C1:C" & Cells(Rows.Count, 1).End(xlUp).Row)
If r.Value <> "" Then
Set shp = ActiveSheet.Shapes.AddPicture(Filename:=r.Value, linktofile:=msoFalse, _
savewithdocument:=msoTrue, Left:=Cells(r.Row, "D").Left + Shrink, _
Top:=Cells(r.Row, "D").Top + Shrink, Width:=-1, Height:=-1)
With shp
.LockAspectRatio = msoTrue
.Width = Columns(2).Width - (2 * Shrink)
Rows(r.Row).RowHeight = .Height + (2 * Shrink)
End With
End If
Next r
Application.ScreenUpdating = True
MoveAndSizeWithCells
MsgBox ("Images Import Complete.")
End Sub
Sub MoveAndSizeWithCells()
Dim xPic As Picture
On Error Resume Next
Application.ScreenUpdating = False
For Each xPic In ActiveSheet.Pictures
xPic.Placement = xlMoveAndSize
Next
Application.ScreenUpdating = True
End Sub

Set all the images horizontally

Good afternoon,
I have the problem.
By using the following function:
Private Sub SizeToRange(ByVal targetShape As Shape, ByVal Target As Range)
' Adjust picture properties
With targetShape
' Check if next line is required...
.LockAspectRatio = msoFalse
.Left = Target.Left + 15
.Top = Target.Top - 4
.Width = Target.Width - 30
.Height = Target.Height
.ZOrder msoSendToBack
'.IncrementRotation Deg
End With
' Adjust picture border properties
With targetShape.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 0, 0)
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = 0
.Transparency = 0
.Visible = msoTrue
.Weight = 1
End With
End Sub
and the code:
Public Sub ResizeChambers()
Dim targetSheet As Worksheet
Dim targetRange As Range
Dim targetShape As Shape
' Define the sheet that has the pictures
Set targetSheet = ThisWorkbook.ActiveSheet
' Define the range the images is going to fit
Set targetRange = targetSheet.Range("E3:I16")
' Loop through each Shape in Sheet
For Each targetShape In targetSheet.Shapes
' Check "picture" word in name
If targetShape.Name Like "*Picture*" Then
' Call the resize function
SizeToRange targetShape, targetRange
targetShape.Flip msoFlipHorizontal
End If
Next targetShape
End Sub
I am trying to set all my images on horizontal way.
As you can see I used both options:
1. targetShape.Flip msoFlipHorizontal for the code
2. .IncrementRotation Deg for function
In both cases doesn't work, because one images are horizontal and another ones are vertical and another way round.
How can I make all of them in horizontal alignment?
You can accomplish this in different ways, by using Shape Range Collection Object, and either use Shepes.SelectAll, or Select each type of shape object, without using the Replace argument, or select a specific Range. Change the type of shape and range as needed. If you have any questions, please ask.
Example 1: Use Shape Range collection Object
Dim shprng As ShapeRange
ActiveSheet.Shapes.SelectAll
Set shprng = Selection.ShapeRange
shprng.Align 3, 0 '3 is the enumeration for msoPicture, and 0 is the enumeration for msoFalse
Example 2: Select the type of shape
Dim shp As Shape
For Each shp In ActiveSheet.Shapes
If shp.Type = 13 Then shp.Select False '13 is the enumeration for msoPicture
Next shp
With Selection.ShapeRange
.Align 3, 0 '3 is the enumeration for msoALignTops, and 0 is the enumeration for msoFalse
End With
Example 3: Use a specific Range
Dim shp As Shape, rng As Range
Set rng = ActiveSheet.Range("D4:O20")
For Each shp In ActiveSheet.Shapes
If Not Intersect(Range(shp.TopLeftCell, shp.BottomRightCell), rng) Is Nothing And shp.Type = 13 Then shp.Select False '13 is the enumeration for msoPicture
Next shp
With Selection.ShapeRange
.Align 3, 0 '3 is the enumeration for msoALignTops, and 0 is the enumeration for msoFalse
End With

Applying custom shortcut for a shape to the current cell I am on

I am trying to create a custom shape with a hotkey. I want it to automatically go to a specific cell I am currently on instead of the same area every single time I run it with my hotkey.
Sub RedSquareShapeNoFill()
'
' RedSquareShapeNoFill Macro
'
' Keyboard Shortcut: Ctrl+q
'
ActiveSheet.Shapes.AddShape(msoShapeRectangle, 197.25, 44.25, 96.75, 26.25). _
Select
Selection.ShapeRange.Fill.Visible = msoFalse
With Selection.ShapeRange.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(255, 0, 0)
.Transparency = 0
End With
With Selection.ShapeRange.Line
.Visible = msoTrue
.Weight = 1.5
End With
End Sub
The current selection could be assigned to a range variable. Then, working with that range, one may use the .Left, .Top, .Width and .Height properties of the range.
Another good idea is to declare the shape as a variable and work with it and not with the Selection, because it is a bad practice - the selection can be a Range or a Shape object:
Sub RedSquareShapeNoFill()
Dim myShape As Shape
Dim wks As Worksheet: Set wks = ActiveSheet
Dim selectionRange As Range
Set selectionRange = Selection
Set myShape = wks.Shapes.AddShape(msoShapeRectangle, _
selectionRange.Left, _
selectionRange.Top, _
selectionRange.Width, _
selectionRange.Height)
With myShape.Line
myShape.Fill.Visible = msoFalse
.Visible = msoTrue
.ForeColor.RGB = RGB(255, 0, 0)
.Transparency = 0
.Visible = msoTrue
.Weight = 1.5
End With
End Sub
You need the top and left of the current cell and plug that into the AddShape parameters
Dim myTop As Double
Dim myLeft As Double
myTop = Selection.Top
myLeft = Selection.Left
ActiveSheet.Shapes.AddShape(msoShapeRectangle, myLeft, myTop, 96.75, 26.25). _
Select

Resources