Vba excel создать картинку

Элемент управления пользовательской формы 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 будет вести себя также, как в 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


Содержание

  1. Метод Shapes.AddPicture (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Пример
  6. Поддержка и обратная связь
  7. Shapes.AddPicture method (Excel)
  8. Syntax
  9. Parameters
  10. Return value
  11. Example
  12. Support and feedback
  13. VBA Excel. Свойство Picture элементов управления
  14. Свойство Picture элементов управления
  15. Синтаксис
  16. Добавление изображений в редакторе VBA
  17. Добавление изображений из кода VBA Excel
  18. VBA Excel. Элемент управления Image
  19. Элемент управления Image
  20. Свойства элемента Image
  21. Примеры добавления изображений
  22. Метод Shapes.AddPicture2 (Excel)
  23. Синтаксис
  24. Параметры
  25. Возвращаемое значение
  26. Поддержка и обратная связь

Метод Shapes.AddPicture (Excel)

Создает рисунок из существующего файла. Возвращает объект Shape , представляющий новый рисунок.

Синтаксис

expression. AddPicture (FileName, LinkToFile, SaveWithDocument, Left, Top, Width, Height)

выражение: переменная, представляющая объект Shapes.

Параметры

Имя Обязательный или необязательный Тип данных Описание
FileName Обязательный String Файл, из которого создается рисунок.
LinkToFile Обязательный MsoTriState Файл, на который необходимо связать ссылку. Используйте msoFalse , чтобы сделать рисунок независимой копией файла. Используйте msoTrue , чтобы связать рисунок с файлом, из которого он был создан.
SaveWithDocument Обязательный MsoTriState Сохранение рисунка вместе с документом. Используйте msoFalse для хранения только сведений о ссылках в документе. Используйте msoTrue , чтобы сохранить связанный рисунок с документом, в который он вставлен. Этот аргумент должен иметь значение msoTrue, если LinkToFile имеет значение msoFalse.
Left Обязательный Single Положение (в точках) левого верхнего угла рисунка относительно левого верхнего угла документа.
Top Обязательный Single Положение (в точках) левого верхнего угла рисунка относительно верхней части документа.
Width Обязательный Single Ширина рисунка в точках (введите -1, чтобы сохранить ширину существующего файла).
Height Обязательный Single Высота рисунка в точках (введите -1, чтобы сохранить высоту существующего файла).

Возвращаемое значение

Shape

Пример

В этом примере изображение, созданное из файла Music.bmp, добавляется в myDocument. Вставленный рисунок связан с файлом, из которого он был создан, и сохраняется с помощью myDocument.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Shapes.AddPicture method (Excel)

Creates a picture from an existing file. Returns a Shape object that represents the new picture.

Syntax

expression.AddPicture (FileName, LinkToFile, SaveWithDocument, Left, Top, Width, Height)

expression A variable that represents a Shapes object.

Parameters

Name Required/Optional Data type Description
FileName Required String The file from which the picture is to be created.
LinkToFile Required MsoTriState The file to link to. Use msoFalse to make the picture an independent copy of the file. Use msoTrue to link the picture to the file from which it was created.
SaveWithDocument Required MsoTriState To save the picture with the document. Use msoFalse to store only the link information in the document. Use msoTrue to save the linked picture with the document into which it’s inserted. This argument must be msoTrue if LinkToFile is msoFalse.
Left Required Single The position (in points) of the upper-left corner of the picture relative to the upper-left corner of the document.
Top Required Single The position (in points) of the upper-left corner of the picture relative to the top of the document.
Width Required Single The width of the picture, in points (enter -1 to retain the width of the existing file).
Height Required Single The height of the picture, in points (enter -1 to retain the height of the existing file).

Return value

Shape

Example

This example adds a picture created from the file Music.bmp to myDocument. The inserted picture is linked to the file from which it was created and is saved with myDocument.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Excel. Свойство Picture элементов управления

Добавление изображений на элементы управления пользовательской формы. Свойство Picture. Привязка картинки в редакторе и из кода VBA Excel. Удаление изображения.

Свойство Picture элементов управления

Свойство Picture есть у пользовательской формы и некоторых элементов управления: CheckBox, CommandButton, Frame, Image, Label, OptionButton, ToggleButton. Оно позволяет отобразить на этих объектах изображение с расширением jpg, bmp, gif.

Синтаксис

  • object – пользовательская форма или подходящий элемент управления;
  • pathname – полный путь к изображению.

Добавление изображений в редакторе VBA

Чтобы добавить картинку на форму или элемент управления в редакторе VBA Excel, необходимо в окне Properties выбранного объекта нажать кнопку с тремя точками в поле значений свойства Picture:

Откроется окно проводника, с помощью которого следует выбрать нужное изображение.

Картинка на элементе управления может использоваться вместо надписи или вместе с ней. За выравнивание изображения и положение надписи на объекте отвечает свойство PicturePosition. Подходящее значение свойства PicturePosition проще подобрать в окне Properties выбранного элемента управления.

Добавление изображений из кода VBA Excel

Пример кода VBA Excel, добавляющего надпись и изображение на элемент управления ToggleButton:

Источник

VBA Excel. Элемент управления Image

Элемент управления пользовательской формы Image, используемый в VBA Excel для добавления на форму изображения. Свойства элемента управления Image.

Элемент управления Image

Добавить изображение на пользовательскую форму можно и с помощью элемента управления 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 при загрузке пользовательской формы:

Источник

Метод Shapes.AddPicture2 (Excel)

Создает рисунок из существующего файла. Возвращает объект Shape , представляющий новый рисунок.

Синтаксис

expression. AddPicture2 (FileName, LinkToFile, SaveWithDocument, Left, Top, Width, Height, Compress)

выражение: переменная, представляющая объект Shapes.

Параметры

Имя Обязательный или необязательный Тип данных Описание
FileName Обязательный String Файл, из которого создается объект OLE.
LinkToFile Обязательный MsoTriState Определяет, будет ли рисунок связан с файлом, из которого он был создан.
SaveWithDocument Обязательный MsoTriState Определяет, будет ли связанный рисунок сохранен вместе с документом, в который он вставлен. Этот аргумент должен иметь значение msoTrue, если LinkToFile имеет значение msoFalse.
Left Обязательный Single Позиция левого края рисунка по отношению к левому краю листа, измеряемая в точках.
Top Обязательный Single Позиция верхнего края рисунка по отношению к верхнему краю листа, измеряемая в точках.
Width Необязательно Single Ширина рисунка, измеряемая в точках.
Height Необязательно Single Высота рисунка, измеряемая в точках.
Сжать Необязательный MsoPictureCompress Определяет, следует ли сжимать рисунок при вставке.

Возвращаемое значение

Shape

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Code Save AS Picture File Macro

Excel Save As Picture

Not As Easy As You’d Think…

One would think that saving something as a picture file (png, jpg, etc…) inside Excel with VBA would be a pretty straightforward exercise. Unfortunately, the “Save as Picture” functionality only exists for saving images of Charts (called exporting). This leaves saving pictures of shapes, icons, and cell ranges void of any VBA automation.

However, with a little bit of creativity, we can utilize the chart object to store our desired image and use the chart object’s Export function to create the image file that we can manually generate by right-clicking and selecting Save as Picture…

In this article I’ll walk you through the basic concept of what the VBA code is doing and also go through two VBA macro examples pertaining to saving shapes/icons and cell ranges in various file formats.

Methodology

Not many people know this but Charts can actually store shapes/objects inside of them. For example, if you have ever copied a textbox and pasted it while a chart is selected, you’ll notice the textbox object appears to be grouped with the chart. Meaning, if you move the chart to a different location, the textbox would move right along with it. What is actually occurring is the textbox is getting embedded within the chart and is essentially now a component of the chart object (think legend, chart title, chart series, axis, etc…).

Notice that the chart object is selected while selecting the textbox? This indicates the textbox has been embedded into the chart object.

Notice that the chart object is selected while selecting the textbox? This indicates the textbox has been embedded into the chart object.

The fact that charts in Excel can absorb other objects is what we will be utilizing to workaround the fact that shapes and other objects cannot be saved as a picture in VBA.

Before we dive into the VBA code, the concept the macro will be utilizing will be to isolate the object you want to save as a picture file and also generating a blank/empty chart object.

VBA Code To Save As Image File

With those two objects in place, the VBA code will simply paste the desired object into the Chart Object (kind of like converting it into a chart!).

VBA Code To Save As Image File

With this concept in mind, let’s take a look at the VBA code I’ve proposed to get this job done!

Save Shape As A PNG File [VBA Code]

Hopefully the following VBA macro is easily to follow along, but I’ll outline essentially the steps it is doing so you can customize it accordingly if needed.

  1. Determine if a shape is selected, if not, don’t proceed. Store the selected shape to a variable (ActiveShape)

  2. Generate a Chart Object that is the exact same size as the selected shape

  3. Remove the chart’s Fill and Border to make the background transparent

  4. Copy the selected shape and Paste it into the Chart Object

  5. Export the Chart Object as a PNG file and save to the user’s desktop

  6. Delete the chart so it appears like nothing has occurred to the user

Sub SaveShapeAsPicture()
‘PURPOSE: Save a selected shape/icon as a PNG file to computer’s desktop
‘SOURCE: www.thespreadsheetguru.com

Dim cht As ChartObject
Dim ActiveShape As Shape
Dim UserSelection As Variant

‘Ensure a Shape is selected
  On Error GoTo NoShapeSelected
    Set UserSelection = ActiveWindow.Selection
    Set ActiveShape = ActiveSheet.Shapes(UserSelection.Name)
  On Error GoTo 0

‘Create a temporary chart object (same size as shape)
  Set cht = ActiveSheet.ChartObjects.Add( _
    Left:=ActiveCell.Left, _
    Width:=ActiveShape.Width, _
    Top:=ActiveCell.Top, _
    Height:=ActiveShape.Height)

‘Format temporary chart to have a transparent background
  cht.ShapeRange.Fill.Visible = msoFalse
  cht.ShapeRange.Line.Visible = msoFalse

    ‘Copy/Paste Shape inside temporary chart
  ActiveShape.Copy
  cht.Activate
  ActiveChart.Paste

   ‘Save chart to User’s Desktop as PNG File
  cht.Chart.Export Environ(«USERPROFILE») & «Desktop» & ActiveShape.Name & «.png»

‘Delete temporary Chart
  cht.Delete

‘Re-Select Shape (appears like nothing happened!)
  ActiveShape.Select

Exit Sub

‘ERROR HANDLERS
NoShapeSelected:
  MsgBox «You do not have a single shape selected!»
  Exit Sub

End Sub

Save Range As A JPG File [VBA Code]

Hopefully the following VBA macro is easily to follow along, but I’ll outline essentially the steps it is doing so you can customize it accordingly if needed.

  1. Determine if a cell range is selected, if not, don’t proceed.

  2. Copy/Paste the range as a picture and store the picture to a variable (ActiveShape)

  3. Generate a Chart Object that is the exact same size as the selected shape

  4. Remove the chart’s Fill and Border to make the background transparent

  5. Copy the selected shape and Paste it into the Chart Object

  6. Export the Chart Object as a PNG file and save to the user’s desktop

  7. Delete the generated chart & picture so it appears like nothing has occurred to the user

Sub SaveRangeAsPicture()
‘PURPOSE: Save a selected cell range as a JPG file to computer’s desktop
‘SOURCE: www.thespreadsheetguru.com

Dim cht As ChartObject
Dim ActiveShape As Shape

‘Confirm if a Cell Range is currently selected
  If TypeName(Selection) <> «Range» Then
    MsgBox «You do not have a single shape selected!»
    Exit Sub
  End If

‘Copy/Paste Cell Range as a Picture
  Selection.Copy
  ActiveSheet.Pictures.Paste(link:=False).Select
  Set ActiveShape = ActiveSheet.Shapes(ActiveWindow.Selection.Name)

  ‘Create a temporary chart object (same size as shape)
  Set cht = ActiveSheet.ChartObjects.Add( _
    Left:=ActiveCell.Left, _
    Width:=ActiveShape.Width, _
    Top:=ActiveCell.Top, _
    Height:=ActiveShape.Height)

‘Format temporary chart to have a transparent background
  cht.ShapeRange.Fill.Visible = msoFalse
  cht.ShapeRange.Line.Visible = msoFalse

    ‘Copy/Paste Shape inside temporary chart
  ActiveShape.Copy
  cht.Activate
  ActiveChart.Paste

   ‘Save chart to User’s Desktop as PNG File
  cht.Chart.Export Environ(«USERPROFILE») & «Desktop» & ActiveShape.Name & «.jpg»

‘Delete temporary Chart
  cht.Delete
  ActiveShape.Delete

‘Re-Select Shape (appears like nothing happened!)
  ActiveShape.Select

End Sub

I Hope This Helped!

Hopefully, I was able to explain how you can use VBA to create image files in Excel. If you have any questions about this technique or suggestions on how to improve it, please let me know in the comments section below.

Chris Newman 2020 - TheSpreadsheetGuru

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you some value today and hope to see you back here soon! — Chris

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

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(&lt;path of your picture in local drive&gt;)
        .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

VBA Code Insert Picture – Sample Workbook

vba image

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:
image from vba
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:
Current weather in US: Image loaded from URL

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)

Понравилась статья? Поделить с друзьями:
  • Vba excel создать имя
  • Vba excel создать директорию
  • Vba excel создать диаграмму
  • Vba excel создание файла word
  • Vba excel создание ссылки