【问题标题】:Insert images from folder into cells将文件夹中的图像插入单元格
【发布时间】:2019-08-12 12:50:44
【问题描述】:

我想将一个文件夹的所有图像一张一张地插入到 Excel 中的递增单元格中。

例如,图片1应该插入单元格E1,然后图片2插入单元格E2,等等

我的代码只能将此目录中的一张图片插入硬编码单元格中:

Sub Insert()

Dim myPict As Picture
Dim PictureLoc As String
PictureLoc = "C:\MyFolder\Picture1.png"

With Range("E1")
    Set myPict = ActiveSheet.Pictures.Insert(PictureLoc)
    .RowHeight = myPict.Height
    myPict.Top = .Top
    myPict.Left = .Left
    myPict.Placement = xlMoveAndSize
End With
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    试试……

    Option Explicit
    
    Sub Insert()
    
        Dim strFolder As String
        Dim strFileName As String
        Dim objPic As Picture
        Dim rngCell As Range
    
        strFolder = "C:\Users\Domenic\Pictures\Saved Pictures\" 'change the path accordingly
        If Right(strFolder, 1) <> "\" Then
            strFolder = strFolder & "\"
        End If
    
        Set rngCell = Range("E1") 'starting cell
    
        strFileName = Dir(strFolder & "*.png", vbNormal) 'filter for .png files
    
        Do While Len(strFileName) > 0
            Set objPic = ActiveSheet.Pictures.Insert(strFolder & strFileName)
            With objPic
                .Left = rngCell.Left
                .Top = rngCell.Top
                .Height = rngCell.RowHeight
                .Placement = xlMoveAndSize
            End With
            Set rngCell = rngCell.Offset(1, 0)
            strFileName = Dir
        Loop
    
    End Sub
    

    要将LockAspectRatio属性设置为False,并将图片的宽度设置为单元格的宽度...

    With objPic
        .ShapeRange.LockAspectRatio = False
        .Left = rngCell.Left
        .Top = rngCell.Top
        .Width = rngCell.Width
        .Height = rngCell.RowHeight
        .Placement = xlMoveAndSize
    End With
    

    希望这会有所帮助!

    【讨论】:

    • 你将如何修改它以获取多个图像文件,如 JPG、GIF TIFF 等?你会追加到 strFileName 吗?还是只为要添加的每种文件类型重复后半部分?
    • 您可以使用Dir(strFolder &amp; "*.*", vbNormal) 循环遍历所有文件,然后在Do While/Loop 中测试所需的文件扩展名。
    • 谢谢,这确实将所有图像放入文件夹中,但由于某种原因,某些图像最终只占单元格宽度的一半,而其他图像则获得整个尺寸。这些图像都具有完全相同的尺寸:4672 x 1800 像素。
    • 您可以将图片的宽度设置为单元格的宽度,但您必须将其 ShapeRange 对象的 LockAspectRatio 属性设置为 False。所以图片会填满整个单元格,但它的纵横比不会和原来的一样。这是你想要的吗?
    • 您能否在答案中提供带有纵横比和不带纵横比的代码?
    猜你喜欢
    • 2016-08-04
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多