【问题标题】:Group Shapes by Shape Object in VBA Excel在 VBA Excel 中按形状对象对形状进行分组
【发布时间】:2021-09-28 22:04:28
【问题描述】:

我在 Excel 中使用 VBA 按名称对形状进行分组时遇到问题。
发生这种情况是因为我有多个可以具有相同名称的形状。

以下代码可以重现我的问题。
您可以取消注释行 OriginalShape.Name = "MyShape" 以查看错误。

Sub test()
    
    ' Create Original Shape
    Dim OriginalShape As Shape
    Set OriginalShape = Sheet1.Shapes.AddShape(msoShapeRectangle, 5, 20, 50, 50)
    
    ' Rename Shape to simulate my project
'    OriginalShape.Name = "MyShape" ' Uncomment line to recreate problem
    
    ' Copy and Paste Shape (I believe there is no other way to do this)
    OriginalShape.Copy
    Sheet1.Paste Sheet1.Range("C2")
    
    ' Get Object of Last Pasted Shape
    Dim CloneShape As Shape
    Set CloneShape = Sheet1.Shapes(Sheet1.Shapes.Count)
    
    ' Group Shapes
    Dim ShapeGroup As Shape
    Set ShapeGroup = Sheet1.Shapes.Range(Array(OriginalShape.Name, CloneShape.Name)).Group

End Sub

我知道我也有可能使用形状索引,例如Sheet1.Shapes.Range(Array(1, 2)).Group,但这似乎也不是一个好方法,因为我需要为每个形状(形状索引)存储一个另外的变量从形状对象。

有没有办法以其他方式对形状进行分组,例如通过对象或 ID。 我相信最好的应该是这样的。

Set ShapeGroup = Sheet1.Shapes.Range(Array(OriginalShape, CloneShape)).Group
'OR
Set ShapeGroup = Sheet1.Shapes.Range(Array(OriginalShape.ID, CloneShape.ID)).Group

【问题讨论】:

  • 如果形状名称相同,您的代码如何知道哪些形状需要分组?或者您只想将工作表上的所有形状分组,或者?您的测试代码并没有告诉我们您实际需要做什么...

标签: excel vba shapes


【解决方案1】:

就像 Tim Williams 所说:代码失败,因为 group-array 由相同的名称组成。您需要做的是在创建形状时将索引添加到名称中

这将起作用:

Sub test()
    
   
    Const cntShapes As Long = 2
    
    
    Dim i As Long, shp As Shape, cTarget As Range
    Dim arrShapeNames(1 To cntShapes) As Variant
    
    With Sheet1
        For i = 1 To cntShapes
            Set cTarget = .Cells(1, i)   'adjust this to your needs
            Set shp = .Shapes.AddShape(msoShapeRectangle, cTarget.Left, cTarget.Top, 50, 50)
            shp.Name = "MyShape." & i   'adding the index to the name makes it unique
            arrShapeNames(i) = shp.Name
        Next
    End With
    
    
    ' Group Shapes
    Dim ShapeGroup As Shape
    Set ShapeGroup = Sheet1.Shapes.Range(arrShapeNames).Group

End Sub

【讨论】:

  • 这个想法很棒。我会将其改进为shp.Name = shp.Name & shp.ID。这样,如果某些形状被删除,它将处理得更好。
  • 抱歉 - 我没有看到使用 i-index 的问题 - 但也可以附加形状 ID。如果这个答案是您问题的一个很好的解决方案,如果您选择它作为“答案”会很好 - 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-27
相关资源
最近更新 更多