从范围(对象)中删除单元格

Remove cell from Range (object)

背景
我的代码在范围内进行了一些循环,但是,每个交互都应该在不包括刚刚执行的单元格的范围内执行。我认为更简单的方法是从存储范围中删除单元格。
问题
我无法找到从存储对象中删除单元格的方法
代码
这个问题很笼统,但是,就事情而言,它会是这样的

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

我怀疑你最好使用 For...Each 循环。这应该是一个起点:

Sub Sample()

    Dim RangeToAnalyze As Range
    Dim rngCell as Range

    Set RangeToAnalyze = Range("Selection")

    For each rngCell in RangeToAnalyze
        'Your other code/actions here
    Next rngCell

    'more code here

End Sub

这应该会在每个单元格上执行您的操作并移动到下一个单元格并自动停止在最后一个单元格。

您也可以将其嵌套在另一个 For...Each 循环中以循环不同的范围等等。

一种方法可能是这样

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

要找到第 5 个 "text",您可以使用 .FindNext

    Set ExcludeCell = RangeToAnalyze.Find("text")

    Dim CounterRange As Long
    For CounterRange = 1 To 5
        If Not ExcludeCell Is Nothing Then 
            Select Case CounterRange 
                Case 1: 
                Case 2: 
                Case 3: 
                Case 4: 
                Case 5: 
            End Select
        End If
        Set ExcludeCell = RangeToAnalyze.FindNext
    Next CounterRange
    'If Not ExcludeCell Is Nothing And CounterRange = 5 Then MsgBox ExcludeCell.Address

另一种方法是暂时用其他东西替换找到的 "text"

    For CounterRange = 1 To 5
        Set ExcludeCell = RangeToAnalyze.Find("text")
        If Not ExcludeCell Is Nothing Then 
            Select Case CounterRange 
                Case 1: 
                Case 2: 
                Case 3: 
                Case 4: 
                Case 5: 
            End Select
        End If
    Next CounterRange

    ' use RangeToAnalyze

    RangeToAnalyze.Replace "not text", "text"

替代方案是将 5 个 "text" 范围存储到一个带 Union 的范围内,清除该范围的值,然后在完成后将它们设置回 "text"