通过减去另外两个范围来获得范围

时间:2015-04-09 13:37:40

标签: excel-vba vba excel

我希望通过减去另外两个现有范围来获得新范围。 我们说:Set rng1=Range("A1")Set rng2=Range("A1:A5") 我想计算一个新范围:rng3 = rng2 - rng1。 我试过了Set rng3 = minus(rng2, rng1),但似乎不可能。

1 个答案:

答案 0 :(得分:1)

这是一种使用UDF的方法。它在大范围内可能不是特别快,因为它逐个单元地迭代。我怀疑它会处理大多数情况。

Public Function DisUnion(keep As Range, remove As Range) As Range

    Dim rng_output As Range

    Dim cell As Range
    For Each cell In keep

        'check if given cell is in range to remove
        If Intersect(cell, remove) Is Nothing Then

            'this builds the output and handles first case
            If rng_output Is Nothing Then
                Set rng_output = cell
            Else
                Set rng_output = Union(rng_output, cell)
            End If
        End If
    Next cell

    Set DisUnion = rng_output

End Function

用法

下面单元格的结果是33,这是正确的。它会按预期更新到单元格的更改。

enter image description here