Excel VBA 通过鼠标获取用户选择范围的范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3686787/
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
Excel VBA get range of user selected range by mouse
提问by sdfg
This is not the usedrangeissue.
For example in Excel user selects a range (possibly empty) using mouse, let's say B4:C12
这不是usedrange问题。
例如,在 Excel 中,用户使用鼠标选择一个范围(可能为空),比如B4:C12
And let's say after this without deselecting the range user presses the macro, and macro should tell B4:C12.
并且假设在此之后没有取消选择范围用户按下宏,宏应该告诉B4:C12。
Can anyone show example?
任何人都可以举个例子吗?
The macro should be something along the lines of the following:
宏应该类似于以下内容:
Sub showrng()
MsgBox SelectedRange.Address(ReferenceStyle:=xlA1)
End Sub
回答by Dr. belisarius
Sub macro1()
MsgBox Selection.Address(ReferenceStyle:=xlA1, _
RowAbsolute:=False, ColumnAbsolute:=False)
End Sub
HTH!
哼!
回答by Ajitabh Ranjan
Sub macro1()
MsgBox Selection.Address
End Sub
or
或者
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
回答by wribln
As selections can include several, independent ranges, the following code shows a more complete solution to the problem:
由于选择可以包含多个独立的范围,因此以下代码显示了该问题的更完整解决方案:
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

