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

use*_*750 2 excel vba range selection

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

Kaz*_*wor 5

我认为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
Run Code Online (Sandbox Code Playgroud)