背景
我的代码在范围内执行一些循环,但是,每个交互应该在不包括刚刚执行的单元格的范围内执行。我认为更简单的方法是从存储的范围中删除单元格。
的 问题
我无法找到从存储对象中删除单元格的方法
的 代码
问题是一般性的,但对于事情来说,这就像是
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
答案 0 :(得分:5)
一种方法可能是这个
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
答案 1 :(得分:3)
你最好使用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 ...每个循环中,以循环不同的范围等等。
答案 2 :(得分:1)
要查找第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"