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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21887042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:01:49  来源:igfitidea点击:

Excel VBA: How to add all of the current shapes on a worksheet to a ShapeRange?

excel-vbashapesvbaexcel

提问by Rick supports Monica

Somewhat of a VBA newbie here.

这里有点像 VBA 新手。

It is clear to me how to create a ShapeRangeusing individual or multiple Shapeobjects:

我很清楚如何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))

Is there a way to add ALL of the currently existing shapes on a worksheet to shprng? In other words, is there a method to return a ShapeRangefrom a Shapesobject...? Something like this:

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

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

Thanks!

谢谢!

回答by Tmdean

If you want to create a ShapeRange by selecting all the shapes on a sheet, you would first select them then get the ShapeRange from the Selection object.

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

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

I usually prefer not to use the Selection object in VBA because it tends to be flaky and can cause errors in weird situations. I think a better way to do this is to build an array of Shape indexes and get the ShapeRange using this array.

我通常不喜欢在 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)