2017-08-08 81 views
0

我製作一個日曆,用於檢查項目到期日期的報告以及與日曆匹配的任何日期,然後突出顯示匹配的單元格並寫入日期和名稱項目在月份右邊的2列中。Excel VBA - 如何在循環中將水平範圍向下移動一行

我按周計算,全年12個月。所以,我不想在一年中的每一週都這樣做,我想做一個循環,循環代碼1周,5次。然後把它放在一個循環中,這個循環可以持續12個月。我有一個月的第一週的代碼,並希望將變量「x」添加到範圍,以便我可以在一週後將範圍添加1,範圍將向下移動1行以執行下一週。我一直無法找到將「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 
+0

我發現有點難以看到你想要做什麼,而沒有一張紙樣。每行代表一週嗎? –

+0

如果每行代表一週,我認爲你的問題是你正在覆蓋。嘗試用'For i = 2 To lastRow step 5'替換'For i = 2 To lastRow',並將此循環與'For x = 0 to 4'交換。我的意思是,我循環(步驟5)外部循環,x內部循環。但我可能是錯的。 – CMArg

回答

2

認爲我看你想現在去

範圍(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") ...等等。

應該工作。

相關問題