Excel VBA – 如何将水平范围向下移动一圈

我制作了一个日历,用于检查项目到期date的报告,以及与日历匹配的任何date,然后突出显示匹配的单元格,并在该月份右侧的2列中写入项目的date和名称。

我每周都要这样做,一年中的所有12个月。 所以,而不是一年中的每一周做这个,我想做一个循环,循环的代码为1周,5次。 然后把它放在一个循环中,这个循环可以持续12个月。 我有一个月的第一个星期的代码,并希望将variables“x”添加到范围,以便我可以添加1后,范围将下移1行做下一周。 我一直没能find把“x”放在范围内的方法。

任何帮助将不胜感激这里是我有的代码:

'for january Set januaryRng = ActiveSheet.Range("A2:G2") i = 2 For x = 0 to 4 For Each cell In januaryRng If cell <> "" Then For i = 2 To lastRow If cell.Value = Sheets("Incident Summary Report").Cells(i, "AI").Value Then Sheets("sheet1").Cells(2 + x, "I") = Sheets("sheet1").Cells(2 + x, "I") & Chr(10) & Sheets("Incident Summary Report").Cells(i, "B").Value ElseIf cell.Value = Sheets("Incident Summary Report").Cells(i, "AJ").Value Then Sheets("sheet1").Cells(2 + x, "I") = Sheets("sheet1").Cells(2 + x, "I") & Chr(10) & Sheets("Incident Summary Report").Cells(i, "B").Value End If If cell.Value = Sheets("Incident Summary Report").Cells(i, "AI").Value Then Sheets("sheet1").Cells(2 + x, "H") = Sheets("sheet1").Cells(2 + x, "H") & Chr(10) & Sheets("Incident Summary Report").Cells(i, "AI").Value ElseIf cell.Value = Sheets("Incident Summary Report").Cells(i, "AJ").Value Then Sheets("sheet1").Cells(2 + x, "H") = Sheets("sheet1").Cells(2 + x, "H") & Chr(10) & Sheets("Incident Summary Report").Cells(i, "AJ").Value End If Next i Else End If Next cell Next x 

我明白你现在要去的地方

您正在循环的范围( ActiveSheet.Range("A2:G2") )仅包含从第一周开始的7天(单元格),对吧?

你需要做的是设置一个新的范围,当你的X循环迭代。

这意味着你需要移动这部分:

Set januaryRng = ActiveSheet.Range("A2:G2")

在这部分下面:

For x = 0 to 4

然后你需要改变你的距离参考

"A2:G2""A" & 2 + x, "G" & 2 + x

总而言之,它看起来像

 'for January i = 2 For x = 0 to 4 Set januaryRng = ActiveSheet.Range("A" & 2 + x, "G" & 2 + x) For Each cell In januaryRng If cell <> "" Then ...... 

这样 ,januaryRng将从.Range("A2", "G2")变为.Range("A3", "G3") …等等。

应该工作。