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

背景
我的代码在范围上执行了一些循环,但是,每个交互应该在不包括刚刚执行的单元格的范围内执行。 我认为更简单的方法是从存储的范围中删除单元格。
问题
我一直无法find一种方法从存储的对象中删除单元格

问题是一般的,但事情就是这样的

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 

一种方法可能是这样的

 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 

testingfunction

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

你会更好地使用For …每个循环,我怀疑。 这应该是一个起点:

 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循环来循环不同的范围,以此类推。

要find第五个"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 

另一种select是可以暂时用其他的东西代替find的"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"