使用单元格

时间:2018-03-16 16:07:53

标签: excel vba position cell shape

我有一个Excel日历,其中某些单元格上有一个形状。我希望能够看到哪些单元格具有形状,然后能够提取一些数据。 我搜索了一下,发现最好的选择是使用TopLeftCell.Row,但似乎我的代码出错了。我复制了一段代码并尝试对其进行修改,现在是:

Sub ActiveShapeMacro()

Dim ActiveShape As Shape
Dim UserSelection As Variant

'Pull-in what is selected on screen
  Set UserSelection = ActiveWindow.Selection

'Determine if selection is a shape
  On Error GoTo NoShapeSelected
    Set ActiveShape = ActiveSheet.Shapes(UserSelection.Name)
  On Error Resume Next

'Do Something with your Shape variable
  Cells(Sheet1.Shapes(ActiveShape).TopLeftCell.Row, Sheet1.Shapes(ActiveShape).TopLeftCell.Column).Address
  MsgBox (ActiveShape.Address)

Exit Sub

'Error Handler
NoShapeSelected:
  MsgBox "You do not have a shape selected!"


End Sub

感谢您的帮助! :)

2 个答案:

答案 0 :(得分:2)

错误发生在:

Sheet1.Shapes(ActiveShape)

Shapes正在提供Object(形状本身)时,'Do Something with your Shape variable MsgBox Cells(ActiveShape.TopLeftCell.Row, ActiveShape.TopLeftCell.Column).Address 正在等待字符串(形状名称)

所以使用:

   MsgBox ActiveShape.TopLeftCell.Address

可以简化为:

On Error Resume Next 

此外改变:

On Error GoTo 0

为:

{{1}}

并继续关注那里发生的事情......

答案 1 :(得分:0)

这是一种简单的方法来确定是否已选择范围或形状,以及它是否为Shape:

Sub skjdkffdg()
    Dim s As Shape, typ As String

    typ = TypeName(Selection)

    If typ = "Range" Then
        MsgBox " you have a range selected: " & Selection.Address
    Else
        Set s = ActiveSheet.Shapes(Selection.Name)
        MsgBox "you have a Shape selected: " & s.TopLeftCell.Address
    End If
End Sub

这假设工作表上的唯一内容是形状和范围。