How to position image in a cell range using Excel VBA? - excel

I am trying to move an image within a certain cell range.
I download it and add it up to my specified Excel sheet.
The image looks like this: https://imgur.com/GteP0pM
I would like to resize the image to fit within a range like:
Set r = ws.Range("C17:O34")
To look something like this: https://imgur.com/rddltWk
The image can be a resized manually if need, but I need it within that cell range.
To select the image I tried:
Sub selectImage12()
Worksheets("T-tilbud").Shapes.Range(Array("Picture 12")).Select
End Sub
To move it to the specified cells, I tried:
Set r = ws.Range by following this example:
Dim r As Range
Dim ws As Worksheet
Dim imagePath As String
Dim img As Picture
Set ws = Worksheets("CheckListIndustrialisation")
Set r = ws.Range("A1:D4")
imagePath = "C:\myImage.jpg"
Set img = ws.Pictures.Insert(imagePath)
With img
.ShapeRange.LockAspectRatio = msoFalse
.Top = r.Top
.Left = r.Left
.Width = r.Width
.Height = r.Height
End With

if you want to apply code that you've specified in example to selected "Picture 12" then you can use this new example:
Sub selectImage12()
Dim r As Range
Dim ws As Worksheet
Dim img As ShapeRange
Set ws = Worksheets("T-tilbud")
Set r = ws.Range("A1:D4")
Set img = ws.Shapes.Range(Array("Picture 12"))
With img
.LockAspectRatio = msoFalse
.Top = r.Top
.Left = r.Left
.Width = r.Width
.Height = r.Height
End With
End Sub

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 do I convert URL (in a worksheet) to an image

I have this code to convert a set of URLs in column B to images in column C, but i get the error :
Unable to get the Insert property of the Pictures class. My code :
Private Sub Insert_Pic()
Dim pic As String
Dim myPicture As Picture
Dim rng As Range
Dim item As Range
lRow = ActiveSheet.Cells(Rows.Count, 3).End(xlUp).Row
Set rng = Range("B3:B" & lRow)
For Each item In rng
pic = item.Offset(0, -1)
If pic = "" Then Exit Sub
Set myPicture = ActiveSheet.Pictures.Insert(pic)
With myPicture
.ShapeRange.LockAspectRatio = msoFalse
.Width = item.Width
.Height = item.Height
.Top = Rows(item.Row).Top
.Left = Columns(item.Column).Left
.Placement = xlMoveAndSize
End With
Next
End Sub
Thanks for your help
The algorithm in debugging is to start with something tiny, that works and then to continue.
For a beginning - take this 4 lines only and run them:
Sub TestMe()
Dim myPicAddress As String
myPicAddress = "https://www.vitoshacademy.com/wp-content/uploads/2016/02/va2.png"
Dim myPic As Picture
Set myPic = ActiveSheet.Pictures.Insert(myPicAddress)
End Sub
Then, start working on your code, putting the With-End With part to the code, that already works:
Sub TestMe2()
Dim myPicAddress As String
myPicAddress = "https://www.vitoshacademy.com/wp-content/uploads/2016/02/va2.png"
Dim myPicture As Picture
Set myPicture = ActiveSheet.Pictures.Insert(myPicAddress)
Dim item As Range
Set item = ActiveSheet.Cells(5, 5)
With myPicture
.ShapeRange.LockAspectRatio = msoFalse
.Width = item.Width
.Height = item.Height
.Top = Rows(item.Row).Top
.Left = Columns(item.Column).Left
.Placement = xlMoveAndSize
End With
End Sub
At the end, take a look at the loop and what is passed by as a picture string. Probably the error is hidden somewhere there.

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

how do i offset all the charts in the same worksheet in VBA?

Currently, all my charts are cramped together in the same spot in the same worksheet after running my code. So to view them i have to manually drag and move them to another spot. So is there a way such that i can place all the charts in a orderly manner as shown in expected output? If it is really impossible to do something like this, i am ok with offsetting the graph for every 20 cells even though it is abit inconvenient for viewing but still i attempted to do it but fail to make it happen when i include code with current output with the offsetting code.
Current output(looks like there is 1 chart but all the charts are in the same spot)
Below is the code for my current output
Sub plotgraphs()
'Call meangraph
Call sigmagraph
End Sub
Private Sub sigmagraph()
Dim i As Long, c As Long
Dim shp As Shape
Dim Cht As chart, co As Shape
Dim rngDB As Range, rngX As Range, rngY As Range
Dim Srs As Series
Dim ws As Worksheet
Set ws = Sheets("Data")
Set rngDB = ws.Range("A1").CurrentRegion
Set rngX = rngDB.Columns(1)
Set rngY = rngDB.Columns(4)
Do While Application.CountA(rngY) > 0
Set co = Worksheets("meangraphs").Shapes.AddChart
Set Cht = co.chart
With Cht
.ChartType = xlXYScatter
'remove any data which might have been
' picked up when adding the chart
Do While .SeriesCollection.Count > 0
.SeriesCollection(1).Delete
Loop
'add the data
With .SeriesCollection.NewSeries()
.XValues = rngX.Value
.Values = rngY.Value
End With
'formatting...
With Cht.Axes(xlValue)
.MinimumScale = 0
.MaximumScale = 0.5
.TickLabels.NumberFormat = "0.00E+00"
End With
Cht.Axes(xlCategory, xlPrimary).HasTitle = True
Cht.Axes(xlValue, xlPrimary).HasTitle = True
End With
Set rngY = rngY.Offset(0, 2) 'next y values
Loop
Code for offsetting chart for every 20 cells (fail to make it happen)
Dim OutSht As Worksheet
'
Dim PlaceInRange As Range
Set OutSht = ActiveWorkbook.Sheets("sigmagraphs") '<~~ Output sheet
Set PlaceInRange = OutSht.Range("B2:J21") '<~~ Output location
'
' To place charts at a distance between them
For Each chart In Sheets("sigmagraphs").ChartObjects
' OutSht.Paste PlaceInRange
' Code below changes the range itself to something 20 rows below
Set PlaceInRange = PlaceInRange.Offset(20, 0)
Next chart
Expected output
What you are looking for is the .Left and .Top properties of the Shape containing the Chart.
For example, a macro that would setup your charts into a 2-column grid would look like this:
Sub SetupChartsIntoGrid()
Const TopAnchor As Long = 50
Const LeftAnchor As Long = 50
Const HorizontalSpacing As Long = 10
Const VerticalSpacing As Long = 10
Const ChartHeight As Long = 211
Const ChartWidth As Long = 360
Dim shp As Shape
For Each shp In ActiveSheet.Shapes
If shp.Type = msoChart Then
Dim Counter As Long
Counter = Counter + 1
With shp
.Top = TopAnchor + (WorksheetFunction.RoundUp(Counter / 2, 0) - 1) * (VerticalSpacing + ChartHeight)
.Left = LeftAnchor + ((Counter + 1) Mod 2) * (HorizontalSpacing + ChartWidth)
End With
End If
Next
End Sub

Using the filename of workbook to find image with same filename Excel VBA

I was testing importing an image into a worksheet, which has proved successful, how can I use the filename of my workbook, which I store in a range to then look in a preselected directory for the image with the same filename?
My filename is held in Range - LkupFileName
Sub InsertImage()
Dim ws As Worksheet
Dim ImgPath As String
Dim W As Double, H As Double
Dim L As Long, T As Long
Set ws = ThisWorkbook.Sheets("myworksheet")
'~~> File Location of saved JPG
ImgPath = "C:\images.jpg"
With ws
W = 100 '<~~ Width
H = 50 '<~~ Height
L = .Range("H140").Left '<~~ Left Position for image
T = .Range("H140").Top '<~~ Top Position for image
'Copy & Paste Image code
With .Pictures.Insert(ImgPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = W
.Height = H
End With
.Left = L
.Top = T
.Placement = 1
End With
End With
End Sub
Try this one:
Sub InsertImage()
Dim ws As Worksheet
Dim ImgPath As String, ImgName As String
Dim W As Double, H As Double
Dim L As Long, T As Long
Set ws = ThisWorkbook.Sheets("myworksheet")
'~~> File Location of saved JPG
ImgName = ws.Range("LkupFileName").Value
ImgPath = "C:\Foo\Bar\" & ImgName & ".jpg" 'Modify accordingly.
With ws
W = 100 '<~~ Width
H = 50 '<~~ Height
L = .Range("H140").Left '<~~ Left Position for image
T = .Range("H140").Top '<~~ Top Position for image
'Copy & Paste Image code
With .Pictures.Insert(ImgPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = W
.Height = H
End With
.Left = L
.Top = T
.Placement = 1
End With
End With
End Sub
Two things are assumed:
By LkupFileName, I'm assuming this is a named range.
The image will always be found in the directory you specify.
Let us know if this helps. :)

Resources