VBA每天在Excel中写入一个数据范围
我需要在Excel中制作一个表格,要求开始和结束date。 然后,我需要编写一个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
然后,如果它再次运行一个新的date范围,date将追加到列表的底部。 这只是一个简单的例子,在实践中date范围会更大,并且包含几个月。
我真的不知道从哪里开始,所以任何帮助将不胜感激!
正如@Ron Rosenfeld所说,VBA中的date只是一个可以通过简单的数字操作来增加或减less的数字。 这段代码应该做你想要的:
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
也许下面的代码给你一个想法去哪个方向
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行已经包含一个值。 我太懒惰了…