如何使用VBA在Excel工作表中的现有形状之后粘贴Shape?

时间:2012-04-20 09:59:54

标签: excel vba copy-paste shape

我想复制一个Shape并将其粘贴一个已包含一个或多个Shapes的Sheet。我尝试使用以下简单代码:

myShape.Select
Selection.Copy
ActiveWorkbook.Sheets(mySheet).Paste

但是它将它粘贴在工作表中现有的形状上方...

是否有解决方案来检测现有形状的结束或直接粘贴? THX

1 个答案:

答案 0 :(得分:6)

这是你在尝试的吗?

Sub Sample()
    Dim myShape As Shape

    Set myShape = ActiveSheet.Shapes("Rectangle 1")

    myShape.Copy

    ActiveSheet.Paste

    With Selection
        .Top = myShape.Height + 10
        .Left = myShape.Left
    End With
End Sub

如果有更多形状,那么你必须遍历所有形状,然后找到最后一个形状并考虑该形状的.Top.Height

参见此示例

Option Explicit

Sub Sample()
    Dim myShape As Shape, shp As Shape
    Dim sHeight As Double, sTopp As Double

    For Each shp In ActiveSheet.Shapes
        If shp.Top > sTopp Then
            sTopp = shp.Top
            sHeight = shp.Height
        End If
    Next

    Set myShape = ActiveSheet.Shapes("Rectangle 1")

    myShape.Copy

    ActiveSheet.Paste

    With Selection
        .Top = sTopp + sHeight + 10
        .Left = myShape.Left
    End With
End Sub