从用户选择中获取多个范围(Excel VBA)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16817459/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:19:58  来源:igfitidea点击:

Getting multiple ranges from user selection (Excel VBA)

excelvbarangeselection

提问by user2419750

Is it possible to get multiple ranges from the user selection. For example if the user has selected "A1:B2" then held down ctrl and selected "E1:G2" too then can i get the first range to 1 Range variable and the second one to another?

是否可以从用户选择中获得多个范围。例如,如果用户选择了“A1:B2”,然后按住 ctrl 并选择“E1:G2”,那么我可以将第一个范围设置为 1 Range 变量,将第二个范围设置为另一个吗?

回答by Kazimierz Jawor

I think Areascollection is what you are looking for. Here is sample for two non continuous ranges selected:

我认为Areas收藏就是你要找的。以下是选择的两个非连续范围的示例:

Sub testing()
    'testing area 
    Range("A1:A10,E1:E10").Select

    Dim rngFirst As Range
    Dim rngSecond As Range

    Set rngFirst = Selection.Areas(1)
    rngFirst.Select

    'if there is no other separate range within selection to avoid errors
    'which could solved possible problems this way
    On Error Resume Next
    Set rngSecond = Selection.Areas(2)
    rngSecond.Select

End Sub

回答by user2419750

Yes its possible, this is one way to do it:

是的,这是可能的,这是一种方法:

Sub Selected__Ranges()
    Range("A1:B2,E1:G2").Select
    Dim rng
    Set rng = Selection
    Debug.Print rng.Address
End Sub