使用另一个命名范围子集命名范围

时间:2015-09-13 09:26:13

标签: excel vba range subset

我有两个范围rng1 = A1:D10,rng2 = C7:D10,我想在Excel VBA中访问除C7:D10之外的rng1单元格。

2 个答案:

答案 0 :(得分:0)

希望这会对你有帮助..

Sub prac1()
    Set rng1 = Range("A1:D10")
    Set rng2 = Range("C7:D10")
    Dim cell As Range

    For Each cell In rng1
        If Application.Intersect(cell, rng2) Is Nothing Then
            cell.Value = 10

        End If
    Next
End sub

答案 1 :(得分:0)

两个工作表范围的非联盟一直存在问题。我发现辅助函数有助于反转UnionIntersect方法。

Option Explicit

Sub main()
    Dim r1 As Range, r2 As Range, iWant As Range

    With Worksheets("Sheet1")
        Set r1 = .Cells(1, 1).Resize(10, 4) '<~~ Sheet1!A1:D10
        Set r2 = .Cells(7, 3).Resize(4, 2)  '<~~ Sheet1!C7:D10
        Debug.Print r1.Address(0, 0)
        Debug.Print r2.Address(0, 0)
    End With

    Set iWant = whatDoYouWant(r1, r2)
    Debug.Print iWant.Address(0, 0)
    'do something with the iWant range
    Set iWant = Nothing

End Sub

Function whatDoYouWant(rKEEP As Range, rOMIT As Range) As Range
    Dim r As Range, rng As Range

    For Each r In rKEEP
        If Intersect(r, rOMIT) Is Nothing Then
            If rng Is Nothing Then
                Set rng = r
            Else
                Set rng = Union(rng, r)
            End If
        End If
    Next r
    Set whatDoYouWant = rng

End Function

VBE立即窗口的结果:

main
A1:D10
C7:D10
A1:D6,A7:B10