Excel VBA通​​过鼠标获取用户选择范围的范围

时间:2010-09-10 17:25:45

标签: excel vba excel-vba excel-2007 excel-2003

这不是usedrange问题 例如,在Excel中,用户使用鼠标选择一个范围(可能为空),假设 B4:C12

让我们说在此之后没有取消选择范围用户按下宏,宏应该告诉 B4:C12

有人能举例吗?

宏应该是以下几点:

Sub showrng()
    MsgBox SelectedRange.Address(ReferenceStyle:=xlA1)
End Sub

3 个答案:

答案 0 :(得分:12)

Sub macro1()
  MsgBox Selection.Address(ReferenceStyle:=xlA1, _
                           RowAbsolute:=False, ColumnAbsolute:=False)
End Sub

HTH!

答案 1 :(得分:3)

Sub macro1()
  MsgBox Selection.Address
End Sub

Sub macro1()
    Dim addr as String
    addr = Selection.Address
    msgbox addr

    ' Now, as we found the address, according to that... you can also do other operations

End Sub

答案 2 :(得分:1)

由于选择可以包含多个独立范围,因此以下代码显示了该问题的更完整解决方案:

Public Sub SelectionTest()
Dim r As Range
Dim s As String

  Select Case Selection.Areas.Count
  Case 0:
    MsgBox "Nothing selected."
  Case 1:
    MsgBox "Selected range: " & Selection.Areas(1).Address(False, False)
  Case Else
    s = ""
    For Each r In Selection.Areas
      s = s + vbNewLine + r.Address(False, False)
    Next r
    MsgBox "Selected several areas:" & s
  End Select

End Sub