我需要在Excel中创建一个表单,询问开始日期和结束日期。然后,我需要编写一个VBA脚本,在A列的第一个空白单元格中写出该范围内的每一天。
因此,例如,如果给出了:
Start Date: 1/5/2017
End Date: 1/9/2017
结果将是:
1/5/2017
1/6/2017
1/7/2017
1/8/2017
1/9/2017
然后,如果再次使用新的日期范围运行,则日期将附加到列表的底部。这只是一个简短的例子,在实践中,日期范围会更大,并且包含几个月。
我不确定从哪里开始,所以任何帮助都将不胜感激!
答案 0 :(得分:4)
如上所述@Ron Rosenfeld,VBA中的日期只是可以通过简单的数字运算增加或减少的数字。这段代码应该完全符合您的要求:
Dim startDate As Date
Dim endDate As Date
startDate = DateSerial(2017, 1, 1)
endDate = DateSerial(2017, 1, 23)
Dim sheet As Worksheet
Set sheet = Worksheets("Table1")
Dim i As Integer
i = 1
While startDate <= endDate
sheet.Cells(i, 1) = startDate
startDate = startDate + 1
i = i + 1
Wend
答案 1 :(得分:0)
也许以下代码可以让您了解去哪个方向
Sub TestItA()
Dim startDate As Date
Dim endDate As Date
Dim lenBlock As Long
Dim rg As Range
Dim lastRow As Long
startDate = #1/5/2017#
endDate = #3/9/2017#
With ActiveSheet
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
If lastRow = 1 Then
Set rg = .Cells(lastRow, 1)
Else
Set rg = .Cells(lastRow + 1, 1)
End If
End With
lenBlock = endDate - startDate
rg.Value = startDate
rg.AutoFill Destination:=Range(rg, rg.Offset(lenBlock, 0)), Type:=xlFillDefault
End Sub
请注意,在行的情况下lastRow不正确,并且只有第1行已包含值。我太懒了......