从范围中排除多个单元格

时间:2020-02-20 16:57:31

标签: excel vba range

我的问题是如何从范围对象中删除一个或多个单元格?之前我问过类似的问题,有人指出了这个问题:Remove cell from Range (object)

接受的答案:

Function getExcluded(ByVal rngMain As Range, rngExc As Range) As Range
    Dim rngTemp     As Range
    Dim rng         As Range

    Set rngTemp = rngMain
    Set rngMain = Nothing

    For Each rng In rngTemp
        If rng.Address <> rngExc.Address Then
            If rngMain Is Nothing Then
                Set rngMain = rng
            Else
                Set rngMain = Union(rngMain, rng)
            End If
        End If
    Next

    Set getExcluded = rngMain
End Function


Sub test()
    MsgBox getExcluded(Range("A1:M10000"), Range("a10")).Address
End Sub

仅当排除范围是单个单元格时,可接受的答案才有效-至少我尝试过的情况就是这样。我要排除的单元格通常有一个以上的单元格,因此我尝试修改代码:

我的尝试:

Function getExcluded(ByVal rngMain As Range, rngExcl As Range) As Range
    Dim rngTemp As Range
    Dim cellTemp As Range, cellExcl As Range

    Set rngTemp = rngMain
    Set rngMain = Nothing

    For Each cellTemp In rngTemp 'go through all cells in established range
        If Intersect(cellTemp, rngExcl) Is Nothing Then 'check for each cell if it intersects with the range to be excluded; no overlap -> put it into rngMain
            If rngMain Is Nothing Then
                Set rngMain = cellTemp
            Else
                rngMain = Union(rngMain, cellTemp)
            End If

            Debug.Print "cellTemp: " & cellTemp.Address
            Debug.Print "rngMain: " & rngMain.Address

        End If
    Next cellTemp

    Set getExcluded = rngMain


Sub test5()

    getExcluded(Range("A1:D3"), Range("B1:C1")).Select
End Sub

问题似乎发生在Set rngMain = Union(rngMain, rng)行中。我的Debug.Print陈述告诉我,cellTemp正在被迭代。但是,即使执行Union的行并且无论cellTemp是什么,rngMain仍然保持$A$1

我在做什么错?

2 个答案:

答案 0 :(得分:2)

类似的事情,还要设置并集范围

Function testexclude(rngMain As Excel.Range, rngExclude As Excel.Range) As Excel.Range

Dim c As Excel.Range
Dim r As Excel.Range

For Each c In rngMain

    If Intersect(c, rngExclude) Is Nothing Then
        If r Is Nothing Then
            Set r = c
        Else
            Set r = Union(r, c)
        End If
    End If

Next c

Set testexclude = r

End Function

答案 1 :(得分:2)

以@Nathan_Sav为基础。

这将允许添加许多排除范围:

Function testexclude(rngMain As Range, ParamArray rngExclude() As Variant) As Range


Dim i As Long
For i = LBound(rngExclude, 1) To UBound(rngExclude, 1)
    Dim rngexcluderng As Range
    If rngexcluderng Is Nothing Then
        Set rngexcluderng = rngExclude(i)
    Else
        Set rngexcluderng = Union(rngexcluderng, rngExclude(i))
    End If
Next i


Dim c As Range
For Each c In rngMain

    If Intersect(c, rngexcluderng) Is Nothing Then
        Dim r As Range
        If r Is Nothing Then
            Set r = c
        Else
            Set r = Union(r, c)
        End If
    End If

Next c

Set testexclude = r

End Function