vba 获取用户选择的范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4080741/
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
Get User Selected Range
提问by Talguy
How can I get a range of cells selected via user mouse input for further processing using VBA?
如何通过用户鼠标输入选择一系列单元格以使用 VBA 进行进一步处理?
采纳答案by Miyagi Coder
You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):
您可以遍历 Selection 对象以查看选择的内容。这是来自 Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx) 的代码片段:
Sub Count_Selection()
Dim cell As Object
Dim count As Integer
count = 0
For Each cell In Selection
count = count + 1
Next cell
MsgBox count & " item(s) selected"
End Sub
回答by Michael
Selectionis its own object within VBA. It functions much like a Rangeobject.
Selection在 VBA 中是它自己的对象。它的功能很像一个Range对象。
Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.
但是,Selection 和 Range 并不共享所有相同的属性和方法,因此为了便于使用,可能只需创建一个范围并将其设置为与 Selection 相等,然后您就可以像处理任何其他范围一样以编程方式处理它。
Dim myRange as Range
Set myRange = Selection
For further reading, check out the MSDN article.
如需进一步阅读,请查看MSDN 文章。
回答by Peter Majko
This depends on what you mean by "get the range of selection". If you mean getting the range address(like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.
这取决于您所说的“获取选择范围”是什么意思。如果您的意思是获取范围地址(如“A1:B1”),则使用 Selection 对象的 Address 属性 - 正如 Michael 所说,Selection 对象很像 Range 对象,因此大多数属性和方法都适用于它。
Sub test()
Dim myString As String
myString = Selection.Address
End Sub

