我编写了一个do while循环,该循环很好用,但是当我尝试为其中的每个next循环添加一个do时,它只会在第一个do while循环之后停止。我真的不确定我需要添加/删除什么才能回到正常运行的循环
rgData,rgHeader和RowSum是我的代码前面定义的范围
Dim myCell As Range, c As Range, firstAddress As String
Const strFindMe As String = "Index"
With rgData
Set c = rgHeader.Find(what:=strFindMe, Lookat:=xlPart).Offset(1, 0)
If Not c Is Nothing Then
firstAddress = c.Address
Do
Dim ColIndex As Range
Set ColIndex = Range(c.Address, Cells(Range(c.Address).Offset(MktCt - 1, 0).Row, Range(c.Address).Column))
For Each myCell In ColIndex
myCell.FormulaR1C1 = "=IF(RC[-3]<>"""",RC[-3]/R" & RowSum & "C[-3]*100,"""")"
myCell.NumberFormat = "0"
Next
Set ColIndex = Nothing
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstAddress
End If
End With
我尝试以这种方式编写代码的原因是,因为我收到的报告已经被透视,因此,针对多个人口统计指标可能需要多个“索引”列
目前,这适用于第一列“索引”列,但不会移至下一个“索引”列。
任何想法都会非常有帮助,谢谢
答案 0 :(得分:3)
您的第一个查找针对rgHeader
,但您的.FindNext
引用了rgData
(通过With块)
为简化逻辑,我将查找与处理分开:
Dim matches as Collection, m
Set matches = FindAll(rgHeader, strFindMe)
For Each m in matches
'process m
Next m
执行查找的单独功能:
Public Function FindAll(rng As Range, val As String) As Collection
Dim rv As New Collection, f As Range
Dim addr As String
Set f = rng.Find(what:=val, after:=rng.Cells(rng.Cells.Count), _
LookIn:=xlValues, LookAt:=xlPart)
If Not f Is Nothing Then addr = f.Address()
Do Until f Is Nothing
rv.Add f
Set f = rng.FindNext(after:=f)
If f.Address() = addr Then Exit Do
Loop
Set FindAll = rv
End Function