select范围内的形状。 奇怪的看似随机的结果?
我试图select范围内的形状,但代码的结果是不是我所期望的。 它随机select比预期更多的形状(不在范围内)。
Public Sub ShapeSelection() Dim Sh As Shape Dim selectedOne As Boolean On Error Resume Next With ActiveSheet For Each Sh In .Shapes If Not Application.Intersect(Sh.TopLeftCell, .Range(Selection.Address)) Is Nothing Then If selectedOne = False Then Sh.Select selectedOne = True Else Sh.Select (False) End If End If Next Sh End With End Sub
奇怪的行为是由“Selection.Address”
在循环中,当find第一个形状时,将当前select从范围C3(比如C3)改变为第一个形状
下次通过循环尝试比较(相交)TopLeftCell的地址和形状对象的地址:形状对象本身没有地址(它的TopLeftCell有一个)
但是你走了很长一段路:你不需要使用相交。 下面的代码如你所期望的那样工作:
Option Explicit Public Sub ShapeSelection() Dim Sh As Shape Dim sRng As Range With ActiveSheet Set sRng = Selection For Each Sh In .Shapes If Sh.TopLeftCell.Address = sRng.Address Then Sh.Select Exit For End If Next Sh End With End Sub
编辑 :我只是注意到你以前的问题: 如何select基于范围的多个形状?
交点是完成这个要求所必需的,但是你仍然需要保留对所选单元格的引用:
Option Explicit Public Sub ShapeSelection() Dim Sh As Shape Dim sRng As Range With ActiveSheet If TypeName(Selection) = "Range" Then Set sRng = Selection If sRng.CountLarge = 1 Then For Each Sh In .Shapes Sh.Select False Next Sh Else For Each Sh In .Shapes If Not Application.Intersect(Sh.TopLeftCell, .Range(sRng.Address)) Is Nothing Then Sh.Select False End If Next Sh End If End If End With End Sub