Excel VBA是否将列中的所有形状适配到相应的单元格?

Excel VBA是否将列中的所有形状适配到相应的单元格?,excel,vba,Excel,Vba,我有一本这样的工作簿: Column L L5 = Image L6 = Image L7 = Image L8 = Image 列L将图像复制并粘贴到每个单元格中。老实说,这些图像看起来都有点不匹配 我想将每个图像精确地匹配到单元格中。是否有一种方法可以对列中的所有图像执行此操作,而不必定义每个图像的名称 以下是我尝试过的: Sub FitImageToCell() With Sheet1.Shapes .Left = .TopLeftCell.Left

我有一本这样的工作簿:

     Column L

L5 = Image
L6 = Image
L7 = Image
L8 = Image
列L将图像复制并粘贴到每个单元格中。老实说,这些图像看起来都有点不匹配

我想将每个图像精确地匹配到单元格中。是否有一种方法可以对列中的所有图像执行此操作,而不必定义每个图像的名称

以下是我尝试过的:

Sub FitImageToCell()
    With Sheet1.Shapes
        .Left = .TopLeftCell.Left
        .Top = .TopLeftCell.Top
        .Height = .TopLeftCell.Height
        .Width = .TopLeftCell.Width
    End With
End Sub
但我得到的对象不支持此属性或方法错误

有人能告诉我怎么做吗?

你就快到了。
您只是没有告诉它您正在使用的形状集合中的哪个形状,也没有告诉它在工作表上查看每个形状

此代码将为每个…使用
。下一步
循环浏览形状集合,并使用
shp
变量引用每个形状

Sub FitImageToCell()

    Dim shp As Shape

    For Each shp In Sheet1.Shapes
        With shp
            .Left = .TopLeftCell.Left
            .Top = .TopLeftCell.Top
            .Height = .TopLeftCell.Height
            .Width = .TopLeftCell.Width
        End With
    Next shp

End Sub
如果只想移动一个形状,则可以使用:

Sub FitImageToCell1()

    With Sheet1.Shapes("Rectangle 1")
        .Left = .TopLeftCell.Left
        .Top = .TopLeftCell.Top
        .Height = .TopLeftCell.Height
        .Width = .TopLeftCell.Width
    End With

End Sub
Sub FitImageToCell()

    Dim shp As Shape

    For Each shp In Sheet1.Shapes
        With shp
            If .Type = msoAutoShape Then
                If .AutoShapeType = msoShapeRectangle Then
                    .Left = .TopLeftCell.Left
                    .Top = .TopLeftCell.Top
                    .Height = .TopLeftCell.Height
                    .Width = .TopLeftCell.Width
                End If
            End If
        End With
    Next shp

End Sub
最后,如果要移动特定类型的形状,可以使用:

Sub FitImageToCell1()

    With Sheet1.Shapes("Rectangle 1")
        .Left = .TopLeftCell.Left
        .Top = .TopLeftCell.Top
        .Height = .TopLeftCell.Height
        .Width = .TopLeftCell.Width
    End With

End Sub
Sub FitImageToCell()

    Dim shp As Shape

    For Each shp In Sheet1.Shapes
        With shp
            If .Type = msoAutoShape Then
                If .AutoShapeType = msoShapeRectangle Then
                    .Left = .TopLeftCell.Left
                    .Top = .TopLeftCell.Top
                    .Height = .TopLeftCell.Height
                    .Width = .TopLeftCell.Width
                End If
            End If
        End With
    Next shp

End Sub
这里有一个形状类型列表:


这里有一个自选图形类型列表:

谢谢@Shai-我甚至没有注意到我还在
With..End With
块中使用
shp