使用for / each循环,但跳转活动单元格VBA

所以我试图写一个For Each循环来查看整行。 如果它发现“专业”一词复制到下三个单元格。 它是这样做的一部分,但是当它循环时,当然下一个单元格中有“专业”,它只是复制它。 我需要弄清楚怎么说,如果你find“专业”并复制它,跳过4个单元格,并重新开始search…..尝试偏移活动单元格,但没有工作。 有任何想法吗? 谢谢!

Sub CopySpecialtyOver() Dim rngRow As Range Dim Cell As Range Set rngRow = Range("A8:BA8") For Each Cell In rngRow If InStr(1, Cell.Value, "Specialty") Then Cell.Offset(0, 1).Value = Cell.Value Cell.Offset(0, 2).Value = Cell.Value Cell.Offset(0, 3).Value = Cell.Value End If Next Cell End Sub 

给出你当前的代码,以下是如何向后循环:

 Sub CopySpecialtyOver() Dim rngRow As Range Dim Cell As Range Dim cIndex As Long Set rngRow = Range("A8:BA8") For cIndex = rngRow.Columns.Count To rngRow.Column Step -1 Set Cell = Cells(rngRow.Row, cIndex) If InStr(1, Cell.Value, "Specialty", vbTextCompare) Then Cell.Offset(, 1).Resize(, 3).Value = Cell.Value End If Next cIndex End Sub 

你可以用一个整数迭代来代替'For each':

 Sub CopySpecialtyOver() Dim i As Integer Dim rngRow As Range Dim Cell As Range Set rngRow = Range("A8:BA8") For i = 1 To rngRow.Cells.Count Set Cell = rngRow(1, i) If InStr(1, Cell.Value, "Specialty") Then Cell.Offset(0, 1).Value = Cell.Value Cell.Offset(0, 2).Value = Cell.Value Cell.Offset(0, 3).Value = Cell.Value i = i + 3 End If Next i End Sub 

非常感谢! 我最终解决了这个问题:

 Sub CopySpecialtyOver() Dim rngRow As Range Dim Cell As Range Set rngRow = Range("A8:BA8") For Each Cell In rngRow If InStr(1, Cell.Value, "Specialty") Then If InStr(1, Cell.Offset(0, -1).Value, "Specialty") Then Else Cell.Offset(0, 1).Value = Cell.Value Cell.Offset(0, 2).Value = Cell.Value Cell.Offset(0, 3).Value = Cell.Value End If End If Next Cell End Sub 

For Each – 正如其他答复所指出的 – 可能不是最好的策略。 尽pipe如此,正如你所要求的那样,这里有一段代码使用了一些内循环控制来克服在这个用例中For Each的缺陷:

 Sub CopySpecialtyOver() Dim rngRow As Range Dim Cell As Range Dim Found As Boolean Dim Cnt As Integer Set rngRow = Range("A8:BA8") Found = False Cnt = 0 For Each Cell In rngRow.Cells If InStr(1, Cell.Value, "Specialty") And Not Found Then ' capture start of sequence - otherwise do nothing Found = True Cnt = 0 Else If Found Then 'if in Found mode increment counter Cnt = Cnt + 1 ' expand using negative offset If Cnt <= 3 Then Cell = Cell.Offset(0, -Cnt).Value End If ' break after 3rd If Cnt = 3 Then Found = False Cnt = 0 End If End If End If Next Cell End Sub 

这个看起来更复杂的代码在垂直运行(而不是水平方向)方面的优势远远超出了单元格的优点,因为For/Each比常规的For/Next