我正在尝试构建一个代码,允许我从多个日期范围生成日期列表,并将日期与相邻的单元格进行匹配。
由于我试图自动执行此过程,我遇到的问题是原始数据在日期范围之间有空行。所以问题是,如何让代码跳过循环中的空行?
这是我到目前为止所做的:
Sub Dates()
Dim dStart As Date
Dim dEnd As Date
Dim dDate As Date
Dim iCol As Integer
Dim iColDate As Integer
iCol = 6
iColDate = 6
Do While Cells(iCol, 3).Value <> ""
dStart = Format(Cells(iCol, 3).Value, "dd/mm/yyyy")
dEnd = Format(Cells(iCol, 4).Value, "dd/mm/yyyy")
For dDate = dStart To dEnd
Cells(iColDate, 7).Value = dDate
Cells(iColDate, 6).Value = Cells(iCol, 2).Value
iColDate = iColDate + 1
Next
iCol = iCol + 1
Loop
End Sub
非常感谢任何帮助。非常感谢!
答案 0 :(得分:0)
不是循环到第一个空行,而是计算最后一行的位置。
Dim lLastRow As Long
lLastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
然后使用索引For..Next
循环而不是Do..While
循环
Dim lIndex as long
For lIndex = 1 to lLastRow
' do stuff here
Next
答案 1 :(得分:0)
尝试使用Rows.Count
代替FOR loop
,这样就可以在运行循环之前检查最后一行,并避免在行C中的单元格为空时被踢出循环:
Sub Dates()
Dim dStart As Date
Dim dEnd As Date
Dim dDate As Date
Dim iColDate As Integer
Dim lastrow As Long
Dim loop1 As Long
lastrow = Cells(Rows.Count, "C").End(xlUp).Row
iColDate = 6
For loop1 = 6 To lastrow
dStart = Format(Cells(iCol, 3).Value, "dd/mm/yyyy")
dEnd = Format(Cells(iCol, 4).Value, "dd/mm/yyyy")
For dDate = dStart To dEnd
Cells(iColDate, 7).Value = dDate
Cells(iColDate, 6).Value = Cells(iCol, 2).Value
iColDate = iColDate + 1
Next
Next loop1
End Sub