Excel VBA:如何将工作表上的所有当前形状添加到ShapeRange?

时间:2014-02-19 16:53:19

标签: excel-vba shapes vba excel

这里有点VBA新手。

我很清楚如何使用单个或多个ShapeRange对象创建Shape

Dim sht As Worksheet
Set sht = MySht
'
'*Add some shapes*
'
Dim shprng As ShapeRange
Set shprng = sht.Shapes.Range(Array(1,2,3))

有没有办法将工作表上所有当前存在的形状添加到shprng?换句话说,是否有一种从ShapeRange对象返回Shapes的方法......?像这样:

Set shprng = sht.Shapes.Range.SelectAll '<--- Does not work: Type Mismatch
Set shprng = sht.Shapes                 '<--- Same error
Set shprng = sht.Shapes.Range           '<--- Error: Argument not optional

谢谢!

2 个答案:

答案 0 :(得分:4)

如果要通过选择工作表上的所有形状来创建ShapeRange,首先要选择它们,然后从Selection对象中获取ShapeRange。

sht.Shapes.Range.SelectAll
Set shprng = Selection.ShapeRange

我通常不喜欢在VBA中使用Selection对象,因为它往往是片状的,并且可能在奇怪的情况下导致错误。我认为更好的方法是构建一个Shape索引数组并使用此数组获取ShapeRange。

Dim shape_index As Variant
Dim i As Long

ReDim shape_index(1 To sht.Shapes.Count)
For i = 1 To UBound(shape_index)
    shape_index(i) = i
Next

Set shprng = sht.Shapes.Range(shape_index)

答案 1 :(得分:0)

在我的 Office 365 中,TmDean 的代码不起作用。有必要将变量显式声明为动态数组。

    Dim shape_index() As Variant    'Dim shape_index() as Long
    Dim i As Long

    ReDim shape_index(1 To sht.Shapes.Count)
    For i = 1 To UBound(shape_index)
        shape_index(i) = i
    Next

    Set shprng = sht.Shapes.Range(shape_index)