Vba вставка картинки в ячейку excel

Вставка существующего рисунка (фигуры, другого объекта) в ячейку Excel с помощью кода VBA. Подгон ячейки под размеры рисунка и фигуры под размеры ячейки.

Подгон ячейки под размеры рисунка

Вставка рисунка в ячейку из кода VBA Excel с подгоном размеров ячейки под размеры фигуры (картинки).

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

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

Код VBA Excel для вставки рисунка в ячейку с подгоном размеров ячейки под размеры фигуры (картинки):

Sub Primer1()

    With Лист20

        .Shapes(«Рисунок 1»).Placement = xlMove

        ‘изменяем ширину ячейки (столбца) в символах до 1/5 ширины рисунка в пунктах

        .Range(«B3»).ColumnWidth = .Shapes(«Рисунок 1»).Width / 5

        ‘изменяем высоту ячейки (строки) до высоты рисунка + 10 точек для отступов

        .Range(«B3»).RowHeight = .Shapes(«Рисунок 1»).Height + 10

        ‘задаем отступ рисунка от левого края ячейки на 5 пунктов

        .Shapes(«Рисунок 1»).Left = .Range(«B3»).Left + 5

        ‘задаем отступ рисунка от верхнего края ячейки на 5 пунктов

        .Shapes(«Рисунок 1»).Top = .Range(«B3»).Top + 5

    End With

End Sub

Свойству Placement объекта Shapes присваиваем значение константы xlMove, которое задает возможность перемещать рисунок вместе с ячейками, но не изменять его размеры при изменении размеров ячеек. Доступные константы из коллекции XlPlacement перечислены ниже.

Было:

Стало:

Подгон фигуры под размеры ячейки

Вставка рисунка в ячейку из кода VBA Excel с подгоном размеров картинки (фигуры) под размеры ячейки.

Чтобы сохранить пропорции рисунка при изменении его высоты до высоты ячейки, ширину картинки будем изменять во столько же раз, во сколько и высоту.

Код VBA Excel для вставки рисунков в ячейки с подгоном размеров картинок (фигур) под размеры ячеек:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Sub Primer2()

Dim i As Byte, n As Single

    For i = 1 To 5

        With Лист19

            ‘определяем, во сколько раз будет изменена высота рисунка

            n = .Shapes(i).Height / .Cells(i, 1).Height

            .Shapes(i).Placement = xlMove

            ‘изменяем высоту рисунка до высоты ячейки

            .Shapes(i).Height = .Cells(i, 1).Height

            ‘изменяем ширину рисунка пропорционально изменению его высоты

            .Shapes(i).Width = .Shapes(i).Width / n

            ‘выравниваем рисунок по левому краю ячейки

            .Shapes(i).Left = .Cells(i, 1).Left

            ‘выравниваем рисунок по верхнему краю ячейки

            .Shapes(i).Top = .Cells(i, 1).Top

        End With

    Next

End Sub

Было:

Стало:

Константы из коллекции XlPlacement

Константы из коллекции XlPlacement определяют реакцию рисунка, фигуры или другого объекта из группы «Иллюстрации» на перемещение и изменение размеров ячеек, над которыми рисунок расположен.

Описание констант из коллекции XlPlacement:

Константа Значение Описание
xlMoveAndSize 1 Объект перемещается и изменяет размеры вместе с ячейками
xlMove 2 Объект перемещается вместе с ячейками, но не изменяет размеры
xlFreeFloating 3 Объект не перемещается и не изменяет размеры вместе с ячейками

Требуется макросом поместить изображение (картинку) на лист 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

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's user avatar

SWa

4,32323 silver badges40 bronze badges

asked Oct 17, 2012 at 14:29

Berker Yüceer's user avatar

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

SWa's user avatar

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

Teamothy's user avatar

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

FCastro's user avatar

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

Tristan's user avatar

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

enter image description here

answered Jan 24, 2021 at 18:06

kadrleyn's user avatar

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

DrMarbuse's user avatar

DrMarbuseDrMarbuse

77410 silver badges30 bronze badges

1

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

Aumi

20 / 35 / 14

Регистрация: 08.10.2015

Сообщений: 406

1

Вставка картинки в ячейку программно

07.10.2017, 18:22. Показов 26422. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте,

Есть два столбца: id, рисунок
имя картинки состоит из id. Например, id=111, а рисунок 111.jpg.
Я установила высоту строки=200,
Мой код:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
Public Sub insPic()
 
   Application.ScreenUpdating = False
 
Dim BookID As String, T As String, myDir As String
 
myDir = "C:UsersuserPictures"
ID = Range("A1")
T = ".jpg"
 
ActiveSheet.Shapes.AddPicture Filename:=myDir & ID & T, linktofile:=msoFalse, savewithdocument:=msoTrue, Left:=ActiveCell.Left, Top:=ActiveCell.Top, Width:=200, Height:=200
 
Application.ScreenUpdating = True

Дело в том, что картинка вставится в выделенную ячейку. Как сделать, чтобы картинка была в В2?

Было бы вообще замечательно, если подскажите,как сделать так, чтобы циклом вставлялись картинки? ID будут в А1-А10,а рисунки их соответсвенно в В1-В10. Макрос или процедура неважно.



0



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

07.10.2017, 19:46

2

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
Private Sub Test()
   Application.ScreenUpdating = False
   Dim iPath$, iCell As Range
   iPath = "C:UsersUserPictures"
   For Each iCell In [A1:A10]
       With ActiveSheet.Pictures.Insert(iPath & iCell & ".jpg")
            .Top = iCell(1, 2).Top:     .Left = iCell(1, 2).Left
            .Width = iCell(1, 2).Width: .Height = iCell(1, 2).Height
       End With
    Next
    Application.ScreenUpdating = True
End Sub
Visual Basic
1
2
3
4
5
6
7
8
9
10
Private Sub Test2()
   Application.ScreenUpdating = False
   Dim iPath$, iCell As Range
   iPath = "C:UsersUserPictures"
   For Each iCell In [A1:A10]
       ActiveSheet.Shapes.AddPicture iPath & iCell & ".jpg", _
       False, True, iCell(1, 2).Left, iCell(1, 2).Top, iCell(1, 2).Width, iCell(1, 2).Height
    Next
    Application.ScreenUpdating = True
End Sub

Если не хотите, чтобы исходные размеры картинок менялись, то в первом варианте уберите .Width и .Height, а во втором, вместо ширины и длины ячейки просто укажите -1
Если же размеры картинки всё же нужно подогнать под размеры ячеек, то определять каждый раз ширину столбца в цикле, не имеет особого смысла, проще говоря, это можно сделать один раз (перед циклом), а затем использовать полученное значение.



1



Aumi

20 / 35 / 14

Регистрация: 08.10.2015

Сообщений: 406

08.10.2017, 12:41

 [ТС]

3

pashulka,Благодарю вас за ответ!
Тут дело поменялось, сумеете помочь? Хотят, чтобы это была процедура. Чтобы в ячейке прописывалась формула и вниз тянули.
Не подскажите, как преобразовать? Я начала, вот только не знаю, как возвращаемое значение приткнуть

Visual Basic
1
2
3
4
5
6
7
8
9
10
 Public Function Pic(v)
   Application.ScreenUpdating = False
   Dim iPath$, iCell As Range
   iPath = "C:UsersUserPictures"
 '  For Each iCell In [A1:A2]
       ActiveSheet.Shapes.AddPicture iPath & v & ".jpg", _
       False, True, iCell(1, 2).Left, iCell(1, 2).Top, iCell(1, 2).Width, iCell(1, 2).Height
  '  Next
    Application.ScreenUpdating = True
End Function



0



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

08.10.2017, 13:00

4

Лучший ответ Сообщение было отмечено Aumi как решение

Решение

Visual Basic
1
2
3
4
Public Function Pic(c As Range)
    ActiveSheet.Shapes.AddPicture "C:UsersUserPictures" & c & ".jpg", _
    False, True, c(1, 2).Left, c(1, 2).Top, c(1, 2).Width, c(1, 2).Height
End Function

Если хотите импортировать картинку с привязкой к ячейке с UDF, то :

Visual Basic
1
2
3
4
5
6
7
Public Function Pic(c As Range)
    With Application.Caller 'Application.ThisCell
         ActiveSheet.Shapes.AddPicture _
         "C:UsersUserPictures" & c & ".jpg", _
         False, True, .Left, .Top, .Width, .Height
    End With
End Function



1



Aumi

20 / 35 / 14

Регистрация: 08.10.2015

Сообщений: 406

09.10.2017, 11:10

 [ТС]

5

pashulka, Оба варианта не хотят всавлять картинки.
если я в ячейке пишу =Pic(A1) ,то ошибка значении,
а если второй вариант, то Ошибка-неправильная ссылка на ячейку

Добавлено через 1 час 4 минуты
В первом варианте работает этот

Visual Basic
1
2
3
4
Public Function Pic(c) As Range
     ActiveSheet.Shapes.AddPicture "C:UsersUserPictures" & c & ".jpg", _
    False, True, c(1, 2).Left, c(1, 2).Top, c(1, 2).Width, c(1, 2).Height
End Function

Но не получается тянуть формулу вниз.
Каждый раз приходится прописывать формулу в В1 и В2

Добавлено через 28 минут
Поняла в чем ошибка, короче формулу нужно писать в соседнем столбце, тогда все тянется вниз и картинки вставляются



0



mor_sergey

77 / 11 / 0

Регистрация: 28.03.2018

Сообщений: 828

10.06.2020, 13:48

6

pashulka, pashulka, ребят, ничего подходящего не нахожу…мне нужно по условиям из выпадающих списков строить схемы..картинка в колонке Форма просто для южера…как выглядит….строить нужно из элементов.
пробывал макрокордером….не понял как к это перенять

Visual Basic
1
2
ActiveSheet.Shapes.AddShape(msoShapeFlowchartDecision, 545.25, 39, 72, 48.24). _
        Select



0



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