2017-01-23 26 views
1

我需要在Excel中創建一個表單,要求開始和結束日期。然後,我需要編寫VBA腳本,在A列寫出每一天在該範圍內的第一個空白單元格VBA在Excel中的數據範圍之間寫入每天

因此,舉例來說,如果給定:

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 

然後如果它再次運行一個新的日期範圍,日期將追加到列表的底部。這只是一個簡單的例子,實際上日期範圍會更大並且包含幾個月。

我不太確定從哪裏開始,所以任何幫助將不勝感激!

+4

Excel將日期存儲爲帶'1' ='1 Jan 1900'的數字。所以編碼應該很簡單。請注意,這不是一個免費的代碼寫入服務,但它的存在是爲了幫助其他人嘗試開發代碼或功能。因此,我們希望通過數據例子,嘗試代碼,實際產出,預期產出,解決問題的研究努力等方式看到明確的問題。請閱讀HELP頁面以獲取有關[如何提出好問題]的信息, (http://stackoverflow.com/help/how-to-ask)和[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve) –

回答

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行正確已經包含的值。我太懶了......

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