Хитрости »
6 Февраль 2020 22727 просмотров
Вставить картинку в лист — по списку или выбору из ячейки
Сама по себе задача вставки картинки на листе не сложная и ответ лежит на поверхности: это доступно прямо из меню: Вставка(Insert) -группа Иллюстрации(Illustrations) —Рисунок(Picture):
Кодом VBA вставить тоже не сложно, даже макрорекордер записывает это действие:
Sub InsertPicture() ActiveSheet.Pictures.Insert("G:ДокументыИзображенияExcel_vba_ru.png"). _ Select End Sub
Но что делать, если вставить надо картинку из заранее известной папки, но с изменяющимся именем? А если при этом еще надо не просто вставить — а подогнать размер картинки под размер ячейки? Например, в ячейке А2 название товара(соответствует названию картинки), а в В2 должно быть изображение. Здесь уже посложнее. Но тоже вполне реализуемо при помощи VBA
'--------------------------------------------------------------------------------------- ' Author : The_Prist(Щербаков Дмитрий) ' Профессиональная разработка приложений для MS Office любой сложности ' Проведение тренингов по MS Excel ' https://www.excel-vba.ru ' info@excel-vba.ru ' WebMoney - R298726502453; Яндекс.Деньги - 41001332272872 ' Purpose: вставка в ячейку картинки с подгонкой под размеры ячейки '--------------------------------------------------------------------------------------- Sub InsertPicToCell() 'путь к папке с картинками Const sPicsPath As String = "G:ДокументыИзображения" Dim sPicName As String, sPFName As String, sSpName As String Dim oShp As Shape Dim zoom As Double 'в этой ячейке выпадающий список с именами картинок sPicName = Range("A2").Value 'если имя картинки не задано If sPicName = "" Then Exit Sub End If 'проверяем наличие картинки в папке sPFName = sPicsPath & sPicName If Dir(sPFName, 16) = "" Then Exit Sub End If 'в эту ячейку вставляем картинку With Range("B2") On Error Resume Next 'задаем картинке уникальный адрес, 'привязанный к адресу ячейки sSpName = "_" & .Address(0, 0) & "_autopaste" 'если картинка уже есть - удаляем её Set oShp = ActiveSheet.Shapes(sSpName) If Not oShp Is Nothing Then oShp.Delete End If 'вставляем выбранную картинку Set oShp = ActiveSheet.Shapes.AddPicture(sPFName, False, True, .Left + 1, .Top + 1, -1, -1) 'определяем размеры картинки в зависимости от размера ячейки zoom = Application.Min(.Width / oShp.Width, .Height / oShp.Height) oShp.Height = oShp.Height * zoom - 2 'переименовываем вставленную картинку(чтобы потом можно было заменить) oShp.Name = sSpName End With End Sub
Чтобы использовать код необходимо создать в книге стандартный модуль(переходим в редактор VBA(Alt+F11) —Insert —Module) и вставить в него приведенный выше код. Чтобы картинка вставилась в ячейку, надо записать имя картинки в ячейку A2, нажать сочетание клавиш Alt+F8 и выбрать макрос InsertPicToCell. Не очень удобно, правда?
Значит теперь попробуем сделать так, чтобы при каждом изменении в А2 картинка менялась сама, без необходимости запускать каждый раз код вручную. Для этого придется использовать возможность Excel отслеживать такие события, как изменения ячейки(чтобы лучше понять где это лучше сразу прочитать статью Что такое модуль? Какие бывают модули? и особое внимание уделить описанию про модули листов). Теперь чуть переделываем код:
Private Sub Worksheet_Change(ByVal Target As Range) '--------------------------------------------------------------------------------------- ' Author : The_Prist(Щербаков Дмитрий) ' Профессиональная разработка приложений для MS Office любой сложности ' Проведение тренингов по MS Excel ' https://www.excel-vba.ru ' info@excel-vba.ru ' WebMoney - R298726502453; Яндекс.Деньги - 41001332272872 ' Purpose: вставка в ячейку картинки с подгонкой под размеры ячейки '--------------------------------------------------------------------------------------- 'путь к папке с картинками Const sPicsPath As String = "G:ДокументыИзображения" Dim sPicName As String, sPFName As String, sSpName As String Dim oShp As Shape Dim zoom As Double 'т.к. список с именами картинок у нас в ячейке А2, 'то определяем, что значение изменилось именно в ней ' если в ячейке А2 имена картинок, а список товара в другой ячейке ' то надо заменить А2 на ту, которая изменяется списком или руками If Intersect(Target, Range("A2")) Is Nothing Then 'изменения не в А2 - ничего не делаем, завершаем код Exit Sub End If 'в этой ячейке выпадающий список с именами картинок sPicName = Range("A2").Value 'если имя картинки не задано If sPicName = "" Then Exit Sub End If 'проверяем наличие картинки в папке sPFName = sPicsPath & sPicName If Dir(sPFName, 16) = "" Then Exit Sub End If 'в эту ячейку вставляем картинку With Range("B2") On Error Resume Next 'задаем картинке уникальный адрес, 'привязанный к адресу ячейки sSpName = "_" & .Address(0, 0) & "_autopaste" 'если картинка уже есть - удаляем её Set oShp = ActiveSheet.Shapes(sSpName) If Not oShp Is Nothing Then oShp.Delete End If 'вставляем выбранную картинку Set oShp = ActiveSheet.Shapes.AddPicture(sPFName, False, True, .Left + 1, .Top + 1, -1, -1) 'определяем размеры картинки в зависимости от размера ячейки zoom = Application.Min(.Width / oShp.Width, .Height / oShp.Height) oShp.Height = oShp.Height * zoom - 2 'переименовываем вставленную картинку(чтобы потом можно было заменить) oShp.Name = sSpName End With End Sub
Теперь переходим на лист, где в А2 будет изменяться название картинки -правая кнопка мыши на этом листе —Посмотреть код(View Code). Вставляем код выше. Все, теперь при любом изменении в А2 картинка будет изменяться(если указанный файл будет найден в нужной папке).
Если картинки расположены не в «G:ДокументыИзображения», а в той же папке, что и сама книга с кодом, достаточно эту строку
Const sPicsPath As String = «G:ДокументыИзображения»
заменить такими
Dim sPicsPath As String
sPicsPath = ThisWorkbook.Path & «»
тогда папка с книгой будет определяться автоматически.
Но я понимаю, что куда правильнее в ячейке А2 при помощи выпадающего списка выбирать наименование товара, а в В2 при помощи функции ВПР(VLOOKUP) подтягивать из справочника название картинки и уже по этому названию вставлять картинку. Но подстроить код под это уже не сложно. Приводить его здесь не буду, т.к. можно будет запутаться с описанием списка, функций, где и что. Тем более что сам код практически не отличается. К тому же именно в этой реализации код есть в приложенном к статье файле.
Скачать файл:
Вставить картинку в ячейку (366,9 KiB, 2 392 скачиваний)
И еще часто встречающаяся задача по вставке картинок — это вставка картинок массово. Т.е. вставить картинки на основании значений, записанных в столбце. В данном случае это столбец В. А вставлять картинки будем в столбец С, подгоняя размеры картинок под размер каждой ячейки и проверяя, не вставляли ли мы эту картинку туда ранее
Впрочем, основная часть кода была приведена выше — здесь мы лишь добавим цикл по ячейкам. Так же в этом коде мы используем диалог выбора папки, в котором просматривать картинки:
'--------------------------------------------------------------------------------------- ' Author : The_Prist(Щербаков Дмитрий) ' Профессиональная разработка приложений для MS Office любой сложности ' Проведение тренингов по MS Excel ' https://www.excel-vba.ru ' info@excel-vba.ru ' WebMoney - R298726502453; Яндекс.Деньги - 41001332272872 ' Purpose: вставка в ячейку картинки с подгонкой под размеры ячейки '--------------------------------------------------------------------------------------- Option Explicit Sub InsertPictureByVal() Dim sPicsPath As String Dim sPicName As String, sPFName As String, sSpName As String Dim llastr As Long, lr As Long Dim oShp As Shape Dim zoom As Double 'выбираем путь к папке с картинками With Application.FileDialog(msoFileDialogFolderPicker) .Title = "Выбрать папку с картинками" 'заголовок окна диалога .ButtonName = "Выбрать папку" .Filters.Clear 'очищаем установленные ранее типы файлов .InitialFileName = ThisWorkbook.Path 'назначаем первую папку отображения .InitialView = msoFileDialogViewLargeIcons 'вид диалогового окна If .Show = 0 Then Exit Sub 'показываем диалог sPicsPath = .SelectedItems(1) 'считываем путь к папке End With ' если путь надо указать статичный - вместо диалога прописываем одну строку ' sPicsPath = "C:images" 'проверяем, есть ли слеш после пути к папке 'если нет - добавляем, иначе путь к картинке будет неверный If Right(sPicsPath, 1) <> Application.PathSeparator Then sPicsPath = sPicsPath & Application.PathSeparator End If 'определяем последнюю ячейку по столбцу с именами картинок llastr = Cells(Rows.Count, 2).End(xlUp).Row 'если кроме шапки в столбце с именами картинок ничего нет If llastr < 2 Then Exit Sub End If 'цикл по столбцу с именами картинок For lr = 2 To llastr sPicName = Cells(lr, 2).Value 'проверяем наличие картинки в папке sPFName = sPicsPath & sPicName If Dir(sPFName, 16) <> "" And sPicName <> "" Then 'в эту ячейку вставляем картинку With Cells(lr, 3) 'задаем картинке уникальный адрес, 'привязанный к адресу ячейки sSpName = "_" & .Address(0, 0) & "_autopaste" 'если картинка уже есть - удаляем её Set oShp = Nothing On Error Resume Next Set oShp = ActiveSheet.Shapes(sSpName) If Not oShp Is Nothing Then oShp.Delete End If On Error GoTo 0 'вставляем выбранную картинку Set oShp = ActiveSheet.Shapes.AddPicture(sPFName, False, True, .Left + 1, .Top + 1, -1, -1) 'определяем размеры картинки в зависимости от размера ячейки zoom = Application.Min(.Width / oShp.Width, .Height / oShp.Height) oShp.Height = oShp.Height * zoom - 2 'переименовываем вставленную картинку(чтобы потом можно было заменить) oShp.Name = sSpName End With End If Next End Sub
Прикладываю пример в формате ZIP-архива, т.к. вместе с самим файлом с кодом я приложил папку images, которая содержит картинки, используемые для вставки в файле. Папка images и сам файл с кодом должны быть распакованы в одну папку.
Скачать файл:
Вставить картинку в ячейку (366,9 KiB, 2 392 скачиваний)
Обратная задача — сохранение картинок из листа — уже разбиралась мной в этой статье: Как сохранить картинки из листа Excel в картинки JPG
Так же см.:
Как сохранить картинки из листа Excel в картинки JPG
При вставке из VBA картинки на лист ошибка «Метод paste из класса worksheet завершен неверно»
Как скопировать картинку из примечания?
Копирование картинки из примечания
Статья помогла? Поделись ссылкой с друзьями!
Видеоуроки
Поиск по меткам
Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика
Вставка существующего рисунка (фигуры, другого объекта) в ячейку Excel с помощью кода VBA. Подгон ячейки под размеры рисунка и фигуры под размеры ячейки.
Подгон ячейки под размеры рисунка
Вставка рисунка в ячейку из кода VBA Excel с подгоном размеров ячейки под размеры фигуры (картинки).
Сложность заключается в том, что высота и ширина рисунка (фигуры) и высота ячейки измеряются в точках (пунктах), а ширина ячейки (ширина столбца) измеряется в символах.
Хороший результат при вставке в ячейку небольших изображений дает приравнивание одного символа к пяти точкам.
Код VBA Excel для вставки рисунка в ячейку с подгоном размеров ячейки под размеры фигуры (картинки):
Sub Primer1() With Лист20 .Shapes(«Рисунок 1»).Placement = xlMove ‘изменяем ширину ячейки (столбца) в символах до 1/5 ширины рисунка в пунктах .Range(«B3»).ColumnWidth = .Shapes(«Рисунок 1»).Width / 5 ‘изменяем высоту ячейки (строки) до высоты рисунка + 10 точек для отступов .Range(«B3»).RowHeight = .Shapes(«Рисунок 1»).Height + 10 ‘задаем отступ рисунка от левого края ячейки на 5 пунктов .Shapes(«Рисунок 1»).Left = .Range(«B3»).Left + 5 ‘задаем отступ рисунка от верхнего края ячейки на 5 пунктов .Shapes(«Рисунок 1»).Top = .Range(«B3»).Top + 5 End With End Sub |
Свойству Placement объекта Shapes присваиваем значение константы xlMove, которое задает возможность перемещать рисунок вместе с ячейками, но не изменять его размеры при изменении размеров ячеек. Доступные константы из коллекции XlPlacement перечислены ниже.
Было:
Стало:
Подгон фигуры под размеры ячейки
Вставка рисунка в ячейку из кода VBA Excel с подгоном размеров картинки (фигуры) под размеры ячейки.
Чтобы сохранить пропорции рисунка при изменении его высоты до высоты ячейки, ширину картинки будем изменять во столько же раз, во сколько и высоту.
Код VBA Excel для вставки рисунков в ячейки с подгоном размеров картинок (фигур) под размеры ячеек:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Sub Primer2() Dim i As Byte, n As Single For i = 1 To 5 With Лист19 ‘определяем, во сколько раз будет изменена высота рисунка n = .Shapes(i).Height / .Cells(i, 1).Height .Shapes(i).Placement = xlMove ‘изменяем высоту рисунка до высоты ячейки .Shapes(i).Height = .Cells(i, 1).Height ‘изменяем ширину рисунка пропорционально изменению его высоты .Shapes(i).Width = .Shapes(i).Width / n ‘выравниваем рисунок по левому краю ячейки .Shapes(i).Left = .Cells(i, 1).Left ‘выравниваем рисунок по верхнему краю ячейки .Shapes(i).Top = .Cells(i, 1).Top End With Next End Sub |
Было:
Стало:
Константы из коллекции XlPlacement
Константы из коллекции XlPlacement определяют реакцию рисунка, фигуры или другого объекта из группы «Иллюстрации» на перемещение и изменение размеров ячеек, над которыми рисунок расположен.
Описание констант из коллекции XlPlacement:
Константа | Значение | Описание |
---|---|---|
xlMoveAndSize | 1 | Объект перемещается и изменяет размеры вместе с ячейками |
xlMove | 2 | Объект перемещается вместе с ячейками, но не изменяет размеры |
xlFreeFloating | 3 | Объект не перемещается и не изменяет размеры вместе с ячейками |
I’m adding «.jpg» files to my Excel sheet with the code below :
'Add picture to excel
xlApp.Cells(i, 20).Select
xlApp.ActiveSheet.Pictures.Insert(picPath).Select
'Calgulate new picture size
With xlApp.Selection.ShapeRange
.LockAspectRatio = msoTrue
.Width = 75
.Height = 100
End With
'Resize and make printable
With xlApp.Selection
.Placement = 1 'xlMoveAndSize
'.Placement = 2 'xlMove
'.Placement = 3 'xlFreeFloating
.PrintObject = True
End With
I don’t know what I am doing wrong but it doesn’t get inserted into the right cell, so what should I do to put this picture into a specified cell in Excel?
SWa
4,32323 silver badges40 bronze badges
asked Oct 17, 2012 at 14:29
Berker YüceerBerker Yüceer
6,98618 gold badges67 silver badges102 bronze badges
2
Try this:
With xlApp.ActiveSheet.Pictures.Insert(PicPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 75
.Height = 100
End With
.Left = xlApp.ActiveSheet.Cells(i, 20).Left
.Top = xlApp.ActiveSheet.Cells(i, 20).Top
.Placement = 1
.PrintObject = True
End With
It’s better not to .select anything in Excel, it is usually never necessary and slows down your code.
answered Oct 17, 2012 at 14:42
1
Looking at posted answers I think this code would be also an alternative for someone. Nobody above used .Shapes.AddPicture
in their code, only .Pictures.Insert()
Dim myPic As Object
Dim picpath As String
picpath = "C:Usersphoto.jpg" 'example photo path
Set myPic = ws.Shapes.AddPicture(picpath, False, True, 20, 20, -1, -1)
With myPic
.Width = 25
.Height = 25
.Top = xlApp.Cells(i, 20).Top 'according to variables from correct answer
.Left = xlApp.Cells(i, 20).Left
.LockAspectRatio = msoFalse
End With
I’m working in Excel 2013. Also realized that You need to fill all the parameters in .AddPicture
, because of error «Argument not optional». Looking at this You may ask why I set Height
and Width
as -1, but that doesn’t matter cause of those parameters are set underneath between With
brackets.
Hope it may be also useful for someone
answered Oct 22, 2019 at 9:17
TeamothyTeamothy
1,9903 gold badges15 silver badges24 bronze badges
If it’s simply about inserting and resizing a picture, try the code below.
For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the «right» place and registering its top and left properties values of the dummy onto double variables.
Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.
Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
Dim Pic As Picture, Shp as Shape
Set Pic = wsDestination.Pictures.Insert(FilePath)
Pic.Name = "myPicture"
'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
Set Shp = wsDestination.Shapes("myPicture")
With Shp
.Height = 100
.Width = 75
.LockAspectRatio = msoTrue 'Put this later so that changing height doesn't change width and vice-versa)
.Placement = 1
.Top = 100
.Left = 100
End with
End Sub
Good luck!
answered Mar 14, 2017 at 3:40
FCastroFCastro
5916 silver badges7 bronze badges
1
I have been working on a system that ran on a PC and Mac and was battling to find code that worked for inserting pictures on both PC and Mac. This worked for me so hopefully someone else can make use of it!
Note: the strPictureFilePath and strPictureFileName variables need to be set to valid PC and Mac paths Eg
For PC: strPictureFilePath = «E:Dropbox» and strPictureFileName = «TestImage.jpg» and with Mac: strPictureFilePath = «Macintosh HD:Dropbox:» and strPictureFileName = «TestImage.jpg»
Code as Follows:
On Error GoTo ErrorOccured
shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Select
ActiveSheet.Pictures.Insert(Trim(strPictureFilePath & strPictureFileName)).Select
Selection.ShapeRange.Left = shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Left
Selection.ShapeRange.Top = shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Top + 10
Selection.ShapeRange.LockAspectRatio = msoTrue
Selection.ShapeRange.Height = 130
answered Jul 17, 2016 at 9:31
TristanTristan
1632 silver badges10 bronze badges
Firstly, of all I recommend that the pictures are in the same folder as the workbook.
You need to enter some codes in the Worksheet_Change procedure of the worksheet. For example, we can enter the following codes to add the image that with the same name as the value of cell in column A to the cell in column D:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim pic As Picture
If Intersect(Target, [A:A]) Is Nothing Then Exit Sub
On Error GoTo son
For Each pic In ActiveSheet.Pictures
If Not Application.Intersect(pic.TopLeftCell, Range(Target.Offset(0, 3).Address)) Is Nothing Then
pic.Delete
End If
Next pic
ActiveSheet.Pictures.Insert(ThisWorkbook.Path & "" & Target.Value & ".jpg").Select
Selection.Top = Target.Offset(0, 2).Top
Selection.Left = Target.Offset(0, 3).Left
Selection.ShapeRange.LockAspectRatio = msoFalse
Selection.ShapeRange.Height = Target.Offset(0, 2).Height
Selection.ShapeRange.Width = Target.Offset(0, 3).Width
son:
End Sub
With the codes above, the picture is sized according to the cell it is added to.
Details and sample file here : Vba Insert image to cell
answered Jan 24, 2021 at 18:06
kadrleynkadrleyn
3341 silver badge5 bronze badges
1
I tested both @SWa and @Teamothy solution. I did not find the Pictures.Insert
Method in the Microsoft Documentations and feared some compatibility issues. So I guess, the older Shapes.AddPicture
Method should work on all versions. But it is slow!
On Error Resume Next
'
' first and faster method (in Office 2016)
'
With ws.Pictures.Insert(Filename:=imageFileName, LinkToFile:=msoTrue, SaveWithDocument:=msoTrue)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = destRange.Width
.height = destRange.height '222
End With
.Left = destRange.Left
.Top = destRange.Top
.Placement = 1
.PrintObject = True
.Name = imageName
End With
'
' second but slower method (in Office 2016)
'
If Err.Number <> 0 Then
Err.Clear
Dim myPic As Shape
Set myPic = ws.Shapes.AddPicture(Filename:=imageFileName, _
LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, _
Left:=destRange.Left, Top:=destRange.Top, Width:=-1, height:=destRange.height)
With myPic.OLEFormat.Object.ShapeRange
.LockAspectRatio = msoTrue
.Width = destRange.Width
.height = destRange.height '222
End With
End If
answered Jan 31, 2020 at 15:06
DrMarbuseDrMarbuse
77410 silver badges30 bronze badges
1
Images are what enriches our content, visualizing data enables us to compare results, notice patterns and provide insights. Most Excel files are bereft of any images, presenting raw data supported by boring charts. Dashboard often could use a couple of images here and there to visual a metric or trend. Today shortly on how to dynamically create, embed and delete images from your Excel Workbooks by using only VBA.
We will start by introducing the Shapes AddPicture function:
Shapes.AddPicture function
Syntax
Shapes.AddPicture( _ Filename, LinkToFile, SaveWithDocument, _ Left, Top, Width, Height)
Parameters
Filename
File or URL of the picture to add.
LinkToFile
Use MsoTrue or MsoCTrue by default. Full list here.
SaveWithDocument
Use MsoTrue or MsoCTrue by default. Full list here.
Left
Position (in points) of the upper-left corner of the picture relative to the left corner of the document.
Top
Position (in points) of the upper-left corner of the picture relative to the top corner of the document.
Width
Width of the picture in points.
Height
Height of the picture in points.
Add an Image from VBA using a file
Let’s start with a simple example. Say we want to embed an image into our Excel Worksheet as such:
To simply embed an image from a file we need to add a new Shape using the AddPicture function:
Call ActiveSheet.Shapes.AddPicture("C:UsersUserDesktopfacebook.bmp", _ msoCTrue, msoCTrue, 0, 0, 100, 100)
This will add the image “facebook.bmp” to the upper-top corner of our spreadsheet. The size of the image will be 100×100 points.
Similarly we can add the image using an URL of the current weather conditions in the US:
Call ActiveSheet.Shapes.AddPicture( _ "https://i.imwx.com/images/maps/current/curwx_600x405.jpg", _ msoCTrue, _ msoCTrue, _ 0, 0, 600, 405)
This will load the image from the URL. Can take a couple of seconds to complete. Awesome right?
Now with this you can do cool things. Why not upload your project status/dashboard on a webpage and simply refresh it using VBA?
Deleting / Replacing images using VBA
Often you will want to replace an existing image or remove one. Not as obvious as it seems, you can’t replace an existing image – instead need to delete and recreate using a new picture.
Delete an image from VBA
Just deleting an image can be done like this – based on it’s index:
ActiveSheet.Shapes(1).Delete
Or like this if you need to obtain the Shape by name:
ActiveSheet.Shapes("Picture 1").Delete
Replacing images using VBA
Now let’s see what’s the correct way to replace an image (of similar sizes and location):
fileName = "C:NewImage.bmp" 'Collect the location and size of the image Dim shHeight As Long, shWidth As Long, shTop As Long, shLeft As Long Dim s as Shape, ws as Worksheet Set ws = ActiveSheet Set s = ws.Shapes("Picture 1") shHeight = ws.Height: shWidth = ws.Width: shTop = ws.Top: shLeft = ws.Left 'Delete the image s.Delete 'Recreate the image using same location and size ws.Shapes.AddPicture(fileName, msoCTrue, msoCTrue, shLeft, shTop, shWidth, shHeight)
While it is not often that we have to control pictures or images within Excel, based on the number of Google searches for this topic, it’s clearly something people want to know more about. This post serves as a reference to cover most of the scenarios we’re likely to encounter to copy, insert, move, delete and control pictures.
This code can be used in conjunction with my post about using a user defined function to insert and change pictures based on a cell value, which can be found here: https://exceloffthegrid.com/automatically-change-picture/
Download the example file
I recommend you download the example file for this post. Then you’ll be able to work along with examples and see the solution in action, plus the file will be useful for future reference.
Download the file: 0042 VBA copy insert, move, delete pictures.zip
Adapting the code to your needs
It is unlikely that any of the codes will meet your exact requirements. Every code snippet uses variables to hold either the image, the worksheet, a range or an object. By changing those variables, the code can easily be changed and combined with other code snippets to meet your specific requirements.
Insert an image into a worksheet
The following code will insert an image into the active cell of the active worksheet, keeping the original image’s size.
Sub InsertImage() Dim ws As Worksheet Dim imagePath As String Dim imgLeft As Double Dim imgTop As Double Set ws = ActiveSheet imagePath = "C:UsersmarksDocumentsmyImage.png" imgLeft = ActiveCell.Left imgTop = ActiveCell.Top 'Width & Height = -1 means keep original size ws.Shapes.AddPicture _ fileName:=imagePath, _ LinkToFile:=msoFalse, _ SaveWithDocument:=msoTrue, _ Left:=imgLeft, _ Top:=imgTop, _ Width:=-1, _ Height:=-1 End Sub
Depending on our needs, it may be better to create an image straight into an object variable. Then we can refer to the image by using the variable and do not need to know the name of the image. The following code is an example of this technique.
Sub InsertImageToDeclaredVariable() Dim myImage As Shape Dim ws As Worksheet Dim imagePath As String Dim imgLeft As Double Dim imgTop As Double Set ws = ActiveSheet imagePath = "C:UsersmarksDocumentsmyImage.png" imgLeft = ActiveCell.Left imgTop = ActiveCell.Top Set myImage = ws.Shapes.AddPicture( _ Filename:=imagePath, _ LinkToFile:=msoFalse, _ SaveWithDocument:=msoTrue, _ Left:=imgLeft, _ Top:=imgTop, _ Width:=-1, _ Height:=-1) 'Use the variable for the created image MsgBox myImage.Name End Sub
Image names
The code below will display the name of the last inserted image.
The message box is to illustrate that the code works. Once we have captured the shape as an object in the real world, we would perform other actions on the shape.
Sub GetNameOfLastInsertedImage() Dim myImage As Shape Set myImage = ActiveSheet.Shapes(ActiveSheet.Shapes.Count) MsgBox myImage.Name End Sub
The code below renames an existing image.
Sub RenameImage() Dim myImage As Shape Dim ws As Worksheet Set ws = ActiveSheet Set myImage = ws.Shapes("Picture 2") myImage.Name = "New Image Name" End Sub
Get image properties
The following code demonstrates how to retrieve common image properties
Sub GetImageProperties() Dim myImage As Shape Dim ws As Worksheet Set ws = ActiveSheet Set myImage = ws.Shapes("Picture 1") MsgBox "Top: " & myImage.Top & vbNewLine & _ "Left: " & myImage.Left & vbNewLine & _ "Width: " & myImage.Width & vbNewLine & _ "Height: " & myImage.Height & vbNewLine & _ "Z-Order: " & myImage.ZOrderPosition & vbNewLine & _ "Name: " & myImage.Name & vbNewLine & _ "Top Left Cell: " & myImage.TopLeftCell & vbNewLine End Sub
Delete an image
The following code will delete an image called Picture 1 from the active worksheet.
Sub DeleteImage() Dim myImage As Shape Dim ws As Worksheet Set ws = ActiveSheet Set myImage = ws.Shapes("Picture 1") myImage.Delete End Sub
Make images invisible
Images can be made invisible. They still exist and are part of the workbook, but they are not visible to the user.
Sub MakeImageInvisible() Dim myImage As Shape Dim ws As Worksheet Set ws = ActiveSheet Set myImage = ws.Shapes("Picture 1") myImage.Visible = msoFalse 'Make the image visible again 'myImage.Visible = msoTrue End Sub
Loop through all images on a worksheet
The following code will loop through all the images on the active sheet.
Sub LoopThroughImagesOnWs() Dim shp As Shape Dim ws As Worksheet Set ws = ActiveSheet For Each shp In ws.Shapes If shp.Type = msoPicture Then 'Do something to the image 'Example, show message box MsgBox shp.Name & " is a picture" End If Next shp End Sub
Delete an image
The code below will delete a specific named picture.
Sub DeletePicture() Dim myImage As Shape Set myImage = ActiveSheet.Shapes("Picture 1") myImage.Delete End Sub
Confirm if the selected object is a picture
The code below will check if a specific object is a Picture.
Sub CheckIfSelectionIsPicture() Dim thing As Object Set thing = Selection If TypeName(thing) = "Picture" Then MsgBox "Selection is a picture" Else MsgBox "Selection is NOT a picture" End If End Sub
Linked pictures
Images can be linked to cells or named ranges. This makes the image dynamic; when the contents of the cells change, so does the picture.
Sub MakeImageLinkedPicture() Dim ws As Worksheet Set ws = ActiveSheet ws.Pictures("Picture 1").Formula = "=A1:D10" End Sub
Image placement and locking options
Image behavior can be controlled using the placement option.
Sub ImagePlacementAndLockingOptions() Dim myImage As Shape Dim ws As Worksheet Set ws = ActiveSheet Set myImage = ws.Shapes("Picture 1") 'Image placement options myImage.Placement = xlFreeFloating 'The other placement options are: 'xlMoveAndSize 'xlMove 'Locking images (prevent editing image when worksheet protected) myImage.Locked = True 'The other placement options are: 'myImage.Locked = False End Sub
Rotate images
The following code rotates the image by a specific amount
Sub RotateImageIncremental() Dim myImage As Shape Dim rotationValue As Integer Set myImage = ActiveSheet.Shapes("Picture 1") rotationValue = 45 'Rotate the image by the amount specified by the rotationValue myImage.IncrementRotation (rotationValue) End Sub
The following code rotates the image to a specific amount.
Sub RotateImageAbsolute() Dim myImage As Shape Dim rotationValue As Integer Set myImage = ActiveSheet.Shapes("Picture 2") rotationValue = 90 'Rotate the image to the amount specified by the rotationValue myImage.rotation = rotationValue End Sub
Set image position to the center of a cell
An image is positioned based on the top and left of that image. The following code will set the position so that it appears centered within a specific cell.
Sub CenterInCell() Dim myImage As Shape Dim cellLocation As Range Set myImage = ActiveSheet.Shapes("Picture 1") Set cellLocation = ActiveSheet.Range("B4") myImage.Top = cellLocation.Top + (cellLocation.Height / 2) - (myImage.Height / 2) myImage.Left = cellLocation.Left + (cellLocation.Width / 2) - (myImage.Width / 2) End Sub
Flipping an image horizontally or vertically
Flip the image horizontally:
Sub FlipImageHorizontal() Dim myImage As Shape Set myImage = ActiveSheet.Shapes("Picture 1") myImage.Flip msoFlipHorizontal End Sub
Flip the image vertically:
Sub FlipImageVertical() Dim myImage As Shape Set myImage = ActiveSheet.Shapes("Picture 1") myImage.Flip msoFlipVertical End Sub
Resize an image
The code below locks the aspect ratio; therefore, resizing the width or height will maintain the image’s proportions.
Sub ResizeImageLockAspectRatio() Dim myImage As Shape Dim imageWidth As Double Set myImage = ActiveSheet.Shapes("Picture 1") imageWidth = 100 myImage.LockAspectRatio = msoTrue myImage.Width = imageWidth End Sub
When setting the aspect ratio to msoFalse, the height and width operate independently.
Sub ResizeImageHeightOrWidth() Dim myImage As Shape Dim imageWidth As Double Dim imageHeight as Double Set myImage = ActiveSheet.Shapes("Picture 1") imageWidth = 100 imageHeight = 50 myImage.LockAspectRatio = msoFalse myImage.Width = imageWidth myImage.Height = imageHeight End Sub
The following code positions an image and stretches it to perfectly cover a specified range.
Sub StretchImageToCoverCells() Dim myImage As Shape Dim ws As Worksheet Dim rng As Range Set ws = ActiveSheet Set myImage = ws.Shapes("Picture 1") Set rng = ws.Range("A2:D10") myImage.LockAspectRatio = msoFalse myImage.Left = rng.Left myImage.Top = rng.Top myImage.Width = rng.Width myImage.Height = rng.Height End Sub
Cropping
The code below crops an image based on the distance from the top, left, bottom or right.
Sub CropImage() Dim myImage As Shape Set myImage = ActiveSheet.Shapes("Picture1") myImage.PictureFormat.CropLeft = 50 myImage.PictureFormat.CropTop = 50 myImage.PictureFormat.CropRight = 50 myImage.PictureFormat.CropBottom = 50 End Sub
Changing Z-Order
The image can be moved forward or backward within the stack of objects (known as the Z-Order).
Sub ChangeZOrderRelative() Dim myImage As Shape Set myImage = ActiveSheet.Shapes("Picture 1") myImage.ZOrder msoBringForward 'Alternative send backward 'myImage.ZOrder msoSendBackward End Sub
The Z-Order position cannot be set directly. First, send the image to the back, then move the image forward with a loop. Continue looping until the image reaches the correct Z-Order Position.
Sub ChangeZOrderAbsolute() Dim myImage As Shape Dim imageWidth As Double Dim imageZPosition As Integer Set myImage = ActiveSheet.Shapes("Picture 1") imageZPosition = 3 'Force z-order to zero then bring forward myImage.ZOrder msoSendToBack Do While myImage.zOrderPosition < imageZPosition myImage.ZOrder msoBringForward Loop End Sub
Set the background image
The background image appears behind the cells in the spreadsheet.
Sub SetImageBackground() Dim ws As Worksheet Dim imgPath As String Set ws = ActiveSheet imgPath = "C:UsersmarksDocumentsmyImage.png" ws.SetBackgroundPicture fileName:=imgPath 'Remove the background image 'ws.SetBackgroundPicture fileName:=" End Sub
Save picture from Excel
If we have a picture in an Excel workbook, there is no straightforward way to save it to disk as a picture. A common workaround is to set the picture as the background of a chart area, then export the chart as an image.
Sub SavePictureFromExcel() Dim myPic As Shape Dim tempChartObj As ChartObject Dim savePath As String Set myPic = ActiveSheet.Shapes("Picture 1") Set tempChartObj = ActiveSheet.ChartObjects.Add(0, 0, myPic.Width, myPic.Height) savePath = "C:UsersmarksDownloadsmySavedPic.jpg" 'Copy picture into chart, then export chart myPic.Copy tempChartObj.Chart.ChartArea.Select tempChartObj.Chart.Paste tempChartObj.Chart.Export savePath tempChartObj.Delete End Sub
Conclusion
In this post we have provided over 25 examples to demonstrate how to insert, delete, move and control pictures with VBA. Checkout the other posts on this site which use these techniques:
- 3 ways to change or insert images based cell values
- Creating custom Map Charts using shapes and VBA
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).
Do you need help adapting this post to your needs?
I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:
Требуется макросом поместить изображение (картинку) на лист Excel?
Используйте функцию ВставитьКартинку, которая позволит вам вставить картинку в выбранную ячейку (или диапазон ячеек).
При вызове функции можно задать дополнительные дополнительные параметры, указав, следует ли подгонять картинку (или ячейку) по высоте и ширине.
В этом примере демонстрируются возможные варианты применения функции вставки картинок:
Sub ПримерВставкиИзображенийНаЛист() ПутьКФайлуСКартинками = "D:BMPAboutForm.jpg" ' полный путь к файлу изображения ' вставка картинки в ячейку A5 (размеры картинки и ячейки не меняются) ВставитьКартинку Cells(5, 1), ПутьКФайлуСКартинками ' вставка картинки в ячейку F5 (ячейка подгоняется по ШИРИНЕ под картинку) ВставитьКартинку Cells(5, 6), ПутьКФайлуСКартинками, True ' вставка картинки в ячейку E1 (ячейка подгоняется по ВЫСОТЕ под картинку) ВставитьКартинку [e1], ПутьКФайлуСКартинками, , True ' вставка картинки в ячейку F2 (ячейка принимает размеры картинки) ВставитьКартинку Range("F2"), ПутьКФайлуСКартинками, True, True ' ========================================= ' вставка картинки в ячейку F5 (картинка подгоняется по ШИРИНЕ под ячейку) ВставитьКартинку Cells(5, 6), ПутьКФайлуСКартинками, True, , True ' вставка картинки в ячейку E1 (картинка подгоняется по ВЫСОТЕ под ячейку) ВставитьКартинку [e1], ПутьКФайлуСКартинками, , True, True ' вставка картинки в диапазон a2:e3 (картинка вписывается в диапазон) ВставитьКартинку [a2:e3], ПутьКФайлуСКартинками, True, True, True End Sub
А вот и сама функция (скопируйте этот код в стандартный модуль, чтобы иметь возможность вставки картинок одной строкой кода из любого макроса):
Sub ВставитьКартинку(ByRef PicRange As Range, ByVal PicPath As String, _ Optional ByVal AdjustWidth As Boolean, _ Optional ByVal AdjustHeight As Boolean, _ Optional ByVal AdjustPicture As Boolean = False) ' ========== функция получает в качестве параметров: ==================== ' PicRange - прямоугольный диапазон ячеек, поверх которого будет расположено изображение ' PicPath - полный путь к файлу картинки (файл в формате JPG, BMP, PNG, и т.д.) ' AdjustWidth - если TRUE, то включен режим подбора ширины (подгонка по высоте) ' AdjustHeight - если TRUE, то включен режим подбора высоты (подгонка по ширине) ' AdjustPicture - если TRUE, то подгоняются размеры картинки под ячейку, ' если FALSE (по умолчанию), то изменяются размеры ячейки On Error Resume Next: Application.ScreenUpdating = False ' вставка изображения на лист Dim ph As Picture: Set ph = PicRange.Parent.Pictures.Insert(PicPath) ' совмещаем левый верхний угол ячейки и картинки ph.Top = PicRange.Top: ph.Left = PicRange.Left K_picture = ph.Width / ph.Height ' вычисляем соотношение размеров сторон картинки K_PicRange = PicRange.Width / PicRange.Height ' вычисляем соотношение размеров сторон диапазона ячеек If AdjustPicture Then ' ПОДГОНЯЕМ РАЗМЕРЫ ИЗОБРАЖЕНИЯ под ячейку (оптимальный вариант) ' если AdjustWidth=TRUE, то высоту не трогаем - изменяем ширину If AdjustWidth Then ph.Width = PicRange.Width: ph.Height = ph.Width / K_picture ' если AdjustHeight=TRUE, то ширину не трогаем - изменяем высоту If AdjustHeight Then ph.Height = PicRange.Height: ph.Width = ph.Height * K_picture ' AdjustWidth=TRUE и AdjustHeight=TRUE: вписываем картинку в ячейку (без соблюдения пропорций) If AdjustWidth And AdjustHeight Then ph.Width = PicRange.Width: ph.Height = PicRange.Height Else ' ИЗМЕНЯЕМ РАЗМЕРЫ ЯЧЕЙКИ под размеры изображения (нежелательно при вставке НЕСКОЛЬКИХ картинок...) If AdjustWidth Then ' если AdjustWidth=TRUE, то высоту не трогаем - изменяем ширину PicRange.Cells(1).ColumnWidth = PicRange.Cells(1).ColumnWidth * ph.Width / PicRange.Cells(1).Width While Abs(PicRange.Cells(1).Width - ph.Width) > 0.1 ' точный подбор ширины ячейки PicRange.Cells(1).ColumnWidth = PicRange.Cells(1).ColumnWidth - 0.2 * (PicRange.Cells(1).Width - ph.Width) Wend End If If AdjustHeight Then ' если AdjustHeight=TRUE, то ширину не трогаем - изменяем высоту PicRange.Cells(1).RowHeight = PicRange.Cells(1).RowHeight * ph.Height / PicRange.Cells(1).Height While Abs(PicRange.Cells(1).Height - ph.Height) > 0.1 ' точный подбор высоты ячейки PicRange.Cells(1).RowHeight = PicRange.Cells(1).RowHeight - 0.2 * (PicRange.Cells(1).Height - ph.Height) Wend End If End If End Sub