Excel-使用单元格引用从路径插入图像

时间:2018-09-04 12:18:14

标签: excel image insert

我正在使用下面的VBA根据单元格中的路径从本地文件夹插入图像。

代码来自上一个问题: Insert picture in excel macro which takes the file name as reference

' I set RowHeight in the excel to 125 and Picture Height to 100 so it fits nicely
' into the box that I want.
' That can be changed to suit your needs.
Sub InsertImageFullName()

    Application.ScreenUpdating = False


    Dim pic As String ' File path of a picture
    Dim cl As Range
    Dim i As Integer

    Set Rng = Range("A11:A16") ' Defining input range
    i = 1
    For Each cl In Rng

        pic = cl.Offset(0, 11)  ' Full path of the picture file:
                               ' Located in the same row, third column from A, i.e. column D
        If IsFile(pic) Then

            Set myPicture = ActiveSheet.Pictures.Insert(pic) ' Inserting picture from address in D column
                                                             ' into column A

            With myPicture ' Setting picture properties
                .ShapeRange.LockAspectRatio = msoTrue ' Keep aspect ratio
                .Height = 100 ' Set your own size
                .Top = Rows(cl.Row).Top
                .Left = Columns(cl.Column).Left
                .Placement = xlMoveAndSize
            End With
            CenterMe ActiveSheet.Shapes(i), cl
            i = i + 1
        End If

    Next    ' Looping to the Nth row, defined in:
            ' " Set Rng = Range("A13:A20") "

    Set myPicture = Nothing

    Application.ScreenUpdating = True

End Sub
Sub CenterMe(Shp As Shape, OverCells As Range)

    With OverCells
        Shp.Left = .Left + ((.Width - Shp.Width) / 2)
        Shp.Top = .Top + ((.Height - Shp.Height) / 2)
    End With
End Sub
Function IsFile(ByVal fName As String) As Boolean
'Returns TRUE if the provided name points to an existing file.
'Returns FALSE if not existing, or if it's a folder
    On Error Resume Next
    IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)
End Function

除了两个我无法解决的问题之外,这非常有效。

首先,我已将其分配给CMD按钮,单击该按钮将调用宏,但这很奇怪,它将CMD按钮移至应显示图像的第一个单元格(即第一个结果)。 / p>

例如:我在L11中有一个路径,该路径应在A11中显示图像,然后下放图纸。发生的事情是先移动命令按钮,然后转到带有图像,A13等的A12。奇怪的是!

第二个与我相关的问题是它将图像结果从A11移至A12,然后将A12移至A13等。尽管脚本未声明垂直偏移...该脚本当前仅在运行A11:16在A16中放置两个图像。来自上方单元格的一个和正确的一个。

因此,该循环正在工作并提取正确数量的图像,但是由于CMD按钮移至第一个结果所在的位置,因此似乎会产生伪偏移!

有什么想法吗?使用某些东西而不是CMD来调用宏?

非常感谢 A

0 个答案:

没有答案