从Range(对象)中删除单元格

Sgd*_*dva 4 excel vba excel-vba excel-2013

背景
我的代码在范围内执行一些循环,但是,每个交互应该在不包括刚执行的单元格的范围内执行.我认为更简单的方法是从存储的范围中删除单元格.
问题
我无法找到从存储对象中删除单元格的方法
代码
问题是一般的但是,对于问题,它会像

Sub Sample()
Dim RangeToAnalyze As Range
Dim CounterRange As Long
Dim ExcludeCell As Range 'sample on what is desired to achieve
    Set RangeToAnalyze = Selection 'this is based on some other criteria but, in order to reproduce it easier that's why selection
    For CounterRange = 1 To 5
    Set ExcludeCell = RangeToAnalyze.Find("text")
    'now here I would like to find the next cell, but it should exclude the first one in order to go to the next one
    Set RangeToAnalyze = RangeToAnalyze.Exclude(ExcludeCell) 'this is what I want to do, so when looping it could jump to the next find (This function is "sample" this is what I am looking to do
    Next CounterRange
End Sub
Run Code Online (Sandbox Code Playgroud)

cyb*_*shu 6

一种方法可能就是这样

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

测试功能

Sub test()

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

End Sub
Run Code Online (Sandbox Code Playgroud)

  • @Sgdva 将 `If rng.Address &lt;&gt; rngExc.Address Then` 更改为 `If Intersect(rng, rngExc) Is Nothing Then` (2认同)