Элемент управления пользовательской формы Image, используемый в VBA Excel для добавления на форму изображения. Свойства элемента управления Image.
Image – это элемент управления пользовательской формы, предназначенный для отображения на форме изображения в формате *. bmp, *. gif, *. jpg, *. wmf, *. emf, *. ico, *. dib, *. cur.
Добавить изображение на пользовательскую форму можно и с помощью элемента управления Label, но качество, в некоторых случаях, может быть неудовлетворительным. На скриншоте ниже одинаковые изображения в формате «*. jpg» добавлены с помощью элемента управления Image – слева и Label – справа:
Основное отличие элемента управления Image от элемента управления Label заключается в поведении изображения при уменьшении размеров Image и Label до размеров меньше размеров изображения:
- изображение в элементе управления Image обрезается;
- изображение в элементе управления Label уменьшается с нарушением пропорций, подстраиваясь под новый размер элемента управления.
Изображение в элементе управления Image будет вести себя также, как в Label, если установить свойство Image.PictureSizeMode
равным fmPictureSizeModeStretch
.
Свойства элемента Image
Свойство | Описание |
---|---|
AutoSize | Автоподбор размера элемента управления Image под размер изображения. True – размер автоматически подстраивается под изображение. False – размер элемента управления определяется свойствами Width и Height (по умолчанию), а поведение изображения зависит от свойства PictureSizeMode. |
BackColor | Цвет заливки (фона) элемента управления Image, отображается при отсутствии изображения и на полях вокруг изображения. |
BackStyle | Задает стиль заливки (фона) элемента управления Image: fmBackStyleTransparent (0) – фон прозрачный, fmBackStyleOpaque (1) – фон непрозрачный (по умолчанию). |
BorderColor | Цвет рамки элемента управления. |
BorderStyle | Стиль рамки элемента управления. |
ControlTipText | Текст всплывающей подсказки при наведении курсора на изображение. |
Enabled | Возможность взаимодействия пользователя с элементом управления Image. True – взаимодействие включено, False – отключено. |
Height | Высота элемента управления. |
Left | Расстояние от левого края внутренней границы пользовательской формы до левого края элемента управления. |
Picture | Адрес добавляемого изображения. |
PictureAlignment | Выравнивание изображения на элементе управления Image. |
PictureSizeMode | Способ изменения размеров изображения в зависимости от размеров элемента управления Image. fmPictureSizeModeClip (0) – рисунок обрезается или добавляются поля (по умолчанию), fmPictureSizeModeStretch (1) – рисунок растягивается или сжимается с нарушением пропорций, заполняя собой всю площадь элемента управления Image, fmPictureSizeModeZoom (3) – рисунок растягивается или сжимается с сохранением пропорций и добавлением компенсирующих полей. |
PictureTiling | Задает размещение изображения мозаичным способом по всему элементу управления. True – изображение размещается мозаичным способом, False – изображение размещается обычным способом (по умолчанию). |
SpecialEffect | Определяет внешний вид элемента управления. |
Top | Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края элемента управления. |
Visible | Видимость элемента управления Image. True – элемент управления отображается на пользовательской форме, False – скрыт. |
Width | Ширина элемента управления. |
Примеры добавления изображений
Пример 1
Добавление изображения на элемент управления Image при загрузке пользовательской формы:
Private Sub UserForm_Initialize() Me.Image1.Picture = LoadPicture(«C:ФотографииПриродаБерезовая роща.jpg») End Sub |
Пример 2
Добавление изображения на элемент управления Image по адресу, записанному в ячейку таблицы Excel:
Private Sub CommandButton1_Click() UserForm1.Image1.Picture = LoadPicture(Worksheets(«Лист1»).Cells(1, 6)) End Sub |
Dear Friends,
In this article, I am going to teach you a simple VBA code, which help you in inserting a picture in Excel Sheet. I will also discuss about difference between Inserting a picture in Excel and Embedding a picture in Excel Sheet using Excel VBA.
It is based on request from one of LEM reader who wants to know, How to insert a picture in excel sheet using VBA code It is a very simple one liner code to insert a picture in Excel using vba code.
Insert Picture Using VBA Code
Basically, there are two methods to insert a picture in Excel Sheet
Method 1. ActiveSheet.Pictures.Insert
Method 2. ActiveSheet.Shapes.AddPicture
VBA Code for Inserting Picture in Excel Sheet [Method 1]
Using .Pictures.Insert() method, you can insert a picture in Active sheet. Let see the Syntax of this method:
Syntax of .Pictures.Insert Method
[highlight color=”yellow”]ActiveSheet.Pictures.Insert(‘Picture URL’)[/highlight]
This function requires only one parameter – Full path of the picture to be inserted in Excel Sheet. This is a mandatory parameter here.
For Example:
ActiveSheet.Pictures.Insert(“C:….myPic.jpg”)
Above statement will simply insert myPic.jpg picture in Active sheet in its original Size.
If you want to resize and locate the picture according to you, then use the following statement to resize the image and place it where ever you want in the excel sheet.
1. VBA Code to re-size (height and width) the inserted picture
Below code will set the height and width of the selected picture in worksheet which is inserted using VBA code:
With ActiveSheet.Pictures.Insert("Picture full path")
.Left = 110
.Top = 220
.Width = 123
.Height = 134
End With
Explanation and issues with above Code
Left and Top will be set without any issue.
Later, Width of the image will be set to 123 as specified – Height of the image will be automatically set to a respective height to the width – because AspectRatio of the image is by default set to True
Similarly when control goes to the next statement then it will reset the height to 134 and since, aspect ratio is false, width will be adjusted to new respective value.
Challenge here is that you can NOT set AspectRatio flag of the picture while inserting it. (by above statement)
Therefore, be careful while resizing the picture while inserting it by using the above code
So what is the solution?
Here is the solution…
1. first add the picture in its own size.
2. Store the name of this image (uniquely generated one) in a variable. So that you can refer this picture uniquely later on
3. Using this variable, select that Shape and set the aspect ratio to false
4. Then set the height and width of the picture.
Here is the code now…
Dim nameOfPicture as String
With ActiveSheet.Pictures.Insert("Picture file full path")
.Left = ActiveSheet.Range("photograph").Left + 2
.Top = ActiveSheet.Range("photograph").Top + 2
nameOfPicture= .Name
End With
ActiveSheet.Pictures(profile).Select
With Selection.ShapeRange
.LockAspectRatio = msoFalse
.Width = 123
.Height = 134
End With
2. VBA Code to set the location of the inserted Picture
Here you can either set fixed Left and Top value where you want to place your picture. In this case no matter what is the height and width of the cell in the worksheet, your picture will be always placed at a specific location. But suppose if you want – your picture should always be placed at a specific row and column then you can set the left and top values as follows:
With ActiveSheet.Pictures.Insert(<path of your picture in local drive>)
.Left = ActiveSheet.Range("A1").Left
.Top = ActiveSheet.Range("A1").Top
.Placement = 1
End With
Now your selected picture will always be placed where Column A1 starts from left and Row 1 starts from top. It means even if you change height or width of the Range A1, your picture is always going to be in Range A1 only.
Warning!
This method, simply links the image in to your Excel Sheet. It means, after inserting a picture, using this method, if you send it to another computer, picture will not be displayed and an Error message be displayed.
Therefore, this method is good only when you are going to use this excel sheet always in your own computer.
VBA Code for Embedding Picture in Excel Sheet [Method 2]
Using .Shapes.AddPicture() method, you can insert a picture in Active sheet. This method overcome the challenges of above method. This allows user to Embed the picture with the Excel Workbook itself. It means, even if you share the workbook to other computer… this picture will go with the document and you will be able to see it in other computer as well.
Syntax of .Shapes.AddPicture Method
[highlight color=”yellow”].Shapes.AddPicture( Filename , LinkToFile , SaveWithDocument , Left , Top , Width , Height )[/highlight]
Where:
Filename : (Mandatory) As the names suggests, this is the complete file path of the picture you want to embed to your Excel Sheet
LinkToFile : (Mandatory) MsoTriState- True or False – To set whether you want to create a link to the file?
SaveWithDocument : (Mandatory) MsoTriState – True or False – This is the flag which needs to be set to TRUE to embed the picture with Excel Sheet.
Left : (Mandatory)The position of the upper-left corner of the picture with respect to the upper-left corner of the document.
Top : (Mandatory) The position (in points) of the upper-left corner of the picture with respect to the top of the document.
Width : (Mandatory) The width of the picture you want to set. To keep the picture in its original width provide -1
Height : (Mandatory) The Height of the picture you want to set. To keep the picture in its original Height provide -1
Example:
Following VBA code will Embed this picture with the Excel file and it will display in any computer you sent it.
ActiveSheet.Shapes.AddPicture _
Filename:="full path of your file with extension", _
linktofile:=msoFalse, savewithdocument:=msoCTrue, _
Left:=50, Top:=50, Width:=250, Height:=250
Info !
Therefore .Shapes.AddPicture Method can insert a picture with and without links just simply by passing some flags.
For your practice I have created an Excel workbook which you can download and play around.
VBA Code Insert Picture – Sample Workbook
Хитрости »
6 Февраль 2020 22744 просмотров
Вставить картинку в лист — по списку или выбору из ячейки
Сама по себе задача вставки картинки на листе не сложная и ответ лежит на поверхности: это доступно прямо из меню: Вставка(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
ссылки
статистика
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)
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