Excel vba paste image

When we copy images or any data from the cell there may be a chance that the cell can contain pictures or images along with the text or numeric values. When you use VBA to perform the copy paste method you may find that the picture(s) or an image(s) in the cell is missing in the target cell.

Copy Images from one cell to another cell using excel macro VBA

 Solution

If you want to copy all the objects such as text, images, and string from one cell and paste it into another cell, then you should select the source cell first. After selecting the source cell, use the copy method to copy all the objects inside the cell. Then, use the select method to select the target cell and paste the copied values.

 Condition

Make sure that no part of the image extends out of the source cell. Adjust the size and fit it into the source cell ( Say A1) before executing the macro. Otherwise, the macro will not work

Different Methods

1. VBA Copy paste Images from one cell to another cell on the same sheet

First, activate the sheet and select the source cell. Use the copy method to copy images along with the content and select the Destination cell. Use the Paste method to paste it in the destination cell.

Related Post: Speed up Excel VBA macro by 300% just by adding two functions

2. VBA Copy paste Images from one cell to another cell on a different sheet

First, activate the source cell sheet and then select the source cell. Use the copy method to copy the content. Activate the destination cell sheet and select the destination cell. Use the Paste method to paste it in the destination cell.

Check out the video tutorial

Please let me know your doubts via comments

Recommended Excel VBA books

Excel 2016 Power Programming with VBA

Excel VBA 24-Hour Trainer

Excel VBA: A Beginners’ Guide

About The Author

Rajan

Rajan is a web geek-Blogger-Programmer- working in corporate firm as system analyst engineer. Whenever time permits he used to blog on recent trends in technology, monetizing tips, Programming concepts and technical guides to beginners in amarindaz.

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 Icon
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

Headshot Round

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:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. 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.
  4. 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:

Хитрости »

6 Февраль 2020              22685 просмотров


Вставить картинку в лист — по списку или выбору из ячейки

Сама по себе задача вставки картинки на листе не сложная и ответ лежит на поверхности: это доступно прямо из меню: Вставка(Insert) -группа Иллюстрации(Illustrations)Рисунок(Picture):
Вставка Рисунка в Excel
Кодом 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) —InsertModule) и вставить в него приведенный выше код. Чтобы картинка вставилась в ячейку, надо записать имя картинки в ячейку 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?

Используйте функцию ВставитьКартинку, которая позволит вам вставить картинку в выбранную ячейку (или диапазон ячеек).

При вызове функции можно задать дополнительные дополнительные параметры, указав, следует ли подгонять картинку (или ячейку) по высоте и ширине.

В этом примере демонстрируются возможные варианты применения функции вставки картинок:

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

Содержание

  1. При вставке из VBA картинки на лист ошибка «Метод paste из класса worksheet завершен неверно»
  2. How to Insert, Move & Delete Pictures with VBA
  3. Adapting the code to your needs
  4. Insert an image into a worksheet
  5. Image names
  6. Get image properties
  7. Delete an image
  8. Make images invisible
  9. Loop through all images on a worksheet
  10. Delete an image
  11. Confirm if the selected object is a picture
  12. Linked pictures
  13. Image placement and locking options
  14. Rotate images
  15. Set image position to the center of a cell
  16. Flipping an image horizontally or vertically
  17. Resize an image
  18. Cropping
  19. Changing Z-Order
  20. Set the background image
  21. Save picture from Excel
  22. Conclusion
  23. How to Copy Images from one cell to another using excel macro VBA ?
  24. Different Methods

При вставке из VBA картинки на лист ошибка «Метод paste из класса worksheet завершен неверно»

Ничто в мире не идеально, и Excel тоже. Как и любая программа он порой может сильно удивлять разными «непонятками». Вот очередная шутка: казалось бы простой код по копированию и вставке картинки из листа Excel, который отлично работает в 2010, вылетает в 2016 с ошибкой Метод paste из класса worksheet завершен неверно :

Сам код простой и ошибки в общем-то вызывать не должен:

Sub CopyPastePicture() ActiveWorkbook.Sheets(«PICS»).Shapes(«Picture1»).Copy ActiveWorkbook.Sheets(«MAIN»).Paste End Sub

При этом самое печально то, что это даже не на каждом ПК проявляется. А при пошаговой отладке кода и вовсе пропадает. Т.е. для получения ошибки недостаточно одного Excel 2016, здесь влияет несколько факторов: установленные программы, операционная система, метод выполнения и т.д. и т.п. Разбирать каждый частный случай не представляется возможным. Да и даже если найти причину — что, теперь надо удалять все лишнее, что не понравилось Excel-ю? А почему тогда это лишнее не мешает тому же коду в Excel 2010? А если этот код — часть программы на заказ? Заказчик скажет «Тыжпрограммист» и будет прав — это наша проблема, проблема разработчиков. Мы обязаны знать эти подводные камни или как минимум хоть уметь вовремя их устранять. Поэтому приходится искать обходные пути. Судя по ошибке, сам корень зла где-то по пути от буфера к Excel. Возможно, наша скопированная картинка просто не до конца «прогрузилась» в буфер и надо дождаться завершения этой прогрузки. Текст ошибки несколько укрепляет это предположение. Первый порыв — использовать DoEvents, чтобы передать эстафету операционной системе — дать ей завершить свои процессы, в том числе и обработку буфера обмена:

Sub CopyPastePicture() ActiveWorkbook.Sheets(«PICS»).Shapes(«Picture1»).Copy DoEvents ActiveWorkbook.Sheets(«MAIN»).Paste End Sub

Но это не спасает ситуацию. Равно как не спас и цикл с сотней DoEvents:

Sub CopyPastePicture() Dim i As Long ActiveWorkbook.Sheets(«PICS»).Shapes(«Picture1»).Copy For i = 1 To 100: DoEvents: Next ActiveWorkbook.Sheets(«MAIN»).Paste End Sub

С одной стороны все логично и должно работать. И даже работает, но не всегда — ошибка все равно появлялась чуть ли не в половине случаев. Почему? Потому что дело все же в некорректной работе буфера. И DoEvents хоть и передавал управление — проблемы вовсе не решал. Он просто давал небольшую отсрочку, которая позволяла в ряде случаев картинке догрузиться в буфер и избежать ошибки. Но главная проблема в том, что неизвестно для какого ПК сколько таких циклов надо, потому что неизвестно сколько ждать до полной загрузки картинки в буфер. Неизвестно, т.к. на каждом ПК это может быть разное время. В итоге, помучившись еще какое-то время я нашел «костыльное» решение проблемы через такой код:

Sub CopyPastePicture() ‘сначала очистим буфер, чтобы там точно ничего лишнего не было Application.CutCopyMode = False ‘копируем картинку ActiveWorkbook.Sheets(«PICS»).Shapes(«Picture1»).Copy ‘а теперь разрешаем пропуск всех ошибок! On Error Resume Next Err.Clear ‘очищаем лог ошибок, если они были ‘пробуем вставить нашу картинку ActiveWorkbook.Sheets(«MAIN»).Paste ‘если в момент вставки возникла ошибка ‘ сработает цикл, который будет выполняться до тех пор, ‘ пока что-то все же не вставится Do While Err.Number <> 0 Err.Clear ActiveWorkbook.Sheets(«MAIN»).Paste ‘передаем управление системе DoEvents Loop ‘отключаем пропуск ошибок On Error GoTo 0 ‘опять очищаем буфер — теперь уже от того, что скопировали сами кодом Application.CutCopyMode = False End Sub

Решение основано на том, что мы сначала копируем картинку, а потом пробуем её вставить. Если возникает ошибка — запускаем цикл, в котором пытаемся вставить картинку из буфера до тех пор, пока она все же не будет вставлена. Т.е. пока ошибка возникает — картинка не прогрузилась и цикл работает. Как только картинка прогрузилась в буфер — она вставляется без ошибки и цикл завершается.
И такой подход работает и по скорости не сильно тормозит процесс. Единственное, что неплохо было бы добавить — так это некий счетчик. Вдруг по какой-то причин буфер вообще очистился(ну бывают системные ошибки) или ошибка возникала совсем по другой причине(например, вставка производится на защищенный лист) — тогда получим бесконечный цикл. В этом случае лучше всего код «обернуть» в функцию:

‘————————————————————————————— ‘ Author : The_Prist(Щербаков Дмитрий) ‘ http://www.excel-vba.ru ‘ info@excel-vba.ru ‘ Purpose: Копирует указанную картинку и вставляет на заданный лист ‘ oCopy — картинка, для вставки на лист ‘ wsPaste — лист, на который необходимо вставить картинку ‘————————————————————————————— Function CopyPastePicture(oCopy As Shape, wsPaste As Worksheet) Dim lPasteCnt As Long ‘счетчик вставок ‘сначала очистим буфер, чтобы там точно ничего лишнего не было Application.CutCopyMode = False ‘копируем картинку oCopy.Copy ‘а теперь разрешаем пропуск всех ошибок! On Error Resume Next Err.Clear ‘очищаем лог ошибок, если они были ‘пробуем вставить нашу картинку wsPaste.Paste ‘если в момент вставки возникла ошибка ‘ сработает цикл, который будет выполняться до тех пор, ‘ пока что-то все же не вставиться Do While Err.Number <> 0 Err.Clear wsPaste.Paste ‘передаем управление системе DoEvents ‘сччитаем кол-во вставок lPasteCnt = lPasteCnt + 1 ‘если уже более 1000 вставок сделали ‘ но ошибка не уходит — принудительно завершаем цикл ‘ ошибка при этом будет не нулевой If lPasteCnt > 1000 Then Exit Do End If Loop ‘если вставка прошла успешно — ошибка будет нулевой CopyPastePicture = (Err.Number = 0) ‘отключаем пропуск ошибок On Error GoTo 0 ‘опять очищаем буфер — теперь уже от того, что скопировали сами кодом Application.CutCopyMode = False End Function

тогда можно будет не только вставить картинку, но и получить обратную связь — успешно прошла вставка или нет. Если кажется, что 1000 попыток это много, то можно просто в строке If lPasteCnt > 1000 Then вместо 1000 указать нужное число.
А использовать приведенную функцию можно будет так:

Sub TryPastePicture() If CopyPastePicture(ActiveWorkbook.Sheets(«PICS»).Shapes(«Picture1»), ActiveWorkbook.Sheets(«MAIN»)) = False Then MsgBox «Не удалось вставить картинку», vbInformation, «www.excel-vba.ru» Exit Sub End If End Sub

Т.е. мы вызываем функцию, которая пробует вставить картинку. Если все 1000 попыток были безуспешными, то функция вернет значение False . Если же хоть одна вставка удалась — функция вернет True .
Кстати, функция поможет сделать вставку не только картинки, но и любой другой фигуры, у которой есть метод Copy: рисунок, фигура, диаграмма.

Если тоже столкнулись с такой проблемой — делитесь в комментариях кто как решал и что помогло. Соберем подборку методов 🙂

Статья помогла? Поделись ссылкой с друзьями!

Источник

How to Insert, Move & Delete Pictures with VBA

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.

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.

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.

The code below renames an existing image.

Get image properties

The following code demonstrates how to retrieve common image properties

Delete an image

The following code will delete an image called Picture 1 from the active worksheet.

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.

Loop through all images on a worksheet

The following code will loop through all the images on the active sheet.

Delete an image

The code below will delete a specific named picture.

Confirm if the selected object is a picture

The code below will check if a specific object is a Picture.

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.

Image placement and locking options

Image behavior can be controlled using the placement option.

Rotate images

The following code rotates the image by a specific amount

The following code rotates the image to a specific amount.

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.

Flipping an image horizontally or vertically

Flip the image horizontally:

Flip the image vertically:

Resize an image

The code below locks the aspect ratio; therefore, resizing the width or height will maintain the image’s proportions.

When setting the aspect ratio to msoFalse, the height and width operate independently.

The following code positions an image and stretches it to perfectly cover a specified range.

Cropping

The code below crops an image based on the distance from the top, left, bottom or right.

Changing Z-Order

The image can be moved forward or backward within the stack of objects (known as the Z-Order).

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.

Set the background image

The background image appears behind the cells in the spreadsheet.

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.

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:

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:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. 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.
  4. 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:

Источник

How to Copy Images from one cell to another using excel macro VBA ?

When we copy images or any data from the cell there may be a chance that the cell can contain pictures or images along with the text or numeric values. When you use VBA to perform the copy paste method you may find that the picture(s) or an image(s) in the cell is missing in the target cell.

If you want to copy all the objects such as text, images, and string from one cell and paste it into another cell, then you should select the source cell first. After selecting the source cell, use the copy method to copy all the objects inside the cell. Then, use the select method to select the target cell and paste the copied values.

Make sure that no part of the image extends out of the source cell. Adjust the size and fit it into the source cell ( Say A1) before executing the macro. Otherwise, the macro will not work

Different Methods

1. VBA Copy paste Images from one cell to another cell on the same sheet

First, activate the sheet and select the source cell. Use the copy method to copy images along with the content and select the Destination cell. Use the Paste method to paste it in the destination cell.

2. VBA Copy paste Images from one cell to another cell on a different sheet

First, activate the source cell sheet and then select the source cell. Use the copy method to copy the content. Activate the destination cell sheet and select the destination cell. Use the Paste method to paste it in the destination cell.

Check out the video tutorial

Please let me know your doubts via comments

Recommended Excel VBA books

Источник

Понравилась статья? Поделить с друзьями:
  • Excel vba for pivot table
  • Excel vba paste destination
  • Excel vba for overflow
  • Excel vba overflow run time error 6
  • Excel vba for next error