VBA运行循环,直到达到实例数

我需要运行一个macros来修复excel表格中的年份。 “十一月 – 一月”左边的一年是2010年,但是我加了1加上2011年。然后循环需要find下一个“Nov_Jan”并且做同样的2011 + 1 = 2012.为了停止循环,我知道我需要计算“Nov-Jan”实例的数量并运行多个实例。 所以只有4个“11月 – 1月”,只有4次运行循环。 下面的代码在同一个单元格内运行循环,不会继续寻找下一个“Nov-Jan”。 我无法弄清楚为什么。 我有一个图像显示我需要从“之前” – >“之后”,但我的代码从“之前” – >“我有什么”。

Dim iCount As Integer Dim i As Integer i = 1 iCount = Application.WorksheetFunction.CountIf(Range("B:B"), "Nov - Jan") Cells.Find(what:="Nov - Jan", after:=ActiveCell, LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False _ , SearchFormat:=False).Activate Do Until i > iCount i = i + 1 ActiveCell.Offset(0, -1).Select ActiveCell.Value = ActiveCell.Value + 1 Cells.Find(what:="Nov - Jan", after:=ActiveCell, LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False _ , SearchFormat:=False).Activate Loop 

我需要从“之前” – >“之后”,但我的代码从“之前” – >“我有什么”

在这里输入图像描述

试试这个简单的代码:

 Sub loops() Dim c as range 'Change the "Sheet2" reference to your sheet name. With Worksheets("Sheet2").Range("B:B") Set c = .Find("Nov - Jan", LookIn:=xlValues) If Not c Is Nothing Then firstAddress = c.Address Do c.Offset(, -1) = c.Offset(, -1) + 1 Set c = .FindNext(c) Loop While Not c Is Nothing And c.Address <> firstAddress End If End With End Sub 

当使用find方法时,它有一个内置的下一个函数。 它也可以被分配到一个范围,然后可以被操纵来做需要的事情。

见这里获取更多信息。

在你的代码中,你正在循环,但循环每次重置search,因此它每次只find第一个。