通过excel vba

时间:2018-02-18 15:26:39

标签: excel vba excel-vba

我有一个表单,用户将输入开始和结束日期。在此日期,我需要在另一个工作表DailyData中输入从开始日期到结束日期的所有日期。我使用下面的代码,但不知何故,它不起作用。代码也没有给出任何错误。如何使它工作

Sub day()

Dim MaxGain As Workbook
Dim Main As Worksheet
Dim DailyData As Worksheet

Dim StartDate As Date
Dim EndDate As Date
Dim i As Long


Set MaxGain = Excel.Workbooks("MaxGain.xlsm")
Set Main = MaxGain.Worksheets("Main")
Set DailyData = MaxGain.Worksheets("DailyData")

StartDate = Main.Range("B5").Value
EndDate = Main.Range("B6").Value

i = 1
  For DateLooper = StartDate To EndDate 

     DailyData.Cells(i, "A") = DateLooper

     i = i + 1
  Next DateLooper


End Sub

3 个答案:

答案 0 :(得分:3)

Excel几乎没有在“主页”选项卡中创建系列的方法>编辑>填

Sub Day()
    [DailyData!A1] = [Main!B5].Value
    [DailyData!A:A].DataSeries Stop:=[Main!B6]
End Sub

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-dataseries-method-excel

答案 1 :(得分:1)

Sub day()
    Dim MaxGain As Workbook
    Dim Main As Worksheet
    Dim DailyData As Worksheet
    Dim StartDate As Date, EndDate As Date, newDate as date
    Dim i As Long, DaysBetween as long

    Set MaxGain = Excel.Workbooks("MaxGain.xlsm")
    Set Main = MaxGain.Worksheets("Main")
    Set DailyData = MaxGain.Worksheets("DailyData")
    StartDate = Main.Range("B5").Value
    EndDate = Main.Range("B6").Value
    DaysBetween = DateDiff("d", StartDate, EndDate)
    newDate = StartDate
    for i = 1 to DaysBetween
        DailyData.Cells(i, "A") = newDate
        newDate = DateAdd ("d", 1, newDate)

    next i 
End Sub

答案 2 :(得分:0)

您需要将DateLooper引用为:

Dim DateLooper As Long 

然后在For Loop

DailyData.Cells(i, "A") = StartDate + DateLooper