用于查找日期并在另一张表格中显示的vba代码?

时间:2015-08-25 14:48:23

标签: excel vba excel-vba

我有以下代码,这不是我想做的事情

Sub returnDates()
    Dim StartD As Date, EndD As Date
    StartD = Cells(5, 3)
    EndD = Cells(6, 3)
    For Row = 1 To (EndD - StartD)
        Sheet3.Cells(Row, 3) = StartD + Row - 1

    Next Row
End Sub

此刻它会在另一个工作表上查找开始日期和结束日期。然后它返回介于两者之间的日期。目前虽然它没有显示开始和结束日期,只是介于两者之间。我也在指定我想要显示日期的确切单元格时遇到问题。我想要第一次约会出现在B2

3 个答案:

答案 0 :(得分:0)

试试这个:

Sub returnDates()
    Dim StartD As Date, EndD As Date
    StartD = Cells(5, 3)
    EndD = Cells(6, 3)
    For Row = 0 To (EndD - StartD) + 1
         Sheet3.Cells(Row + 2, 2) = StartD + Row 
    Next Row
End Sub

答案 1 :(得分:0)

在这里,我已声明要使用的工作表并添加了一些注释。

Sub returnDates()
    Dim StartD As Date, EndD As Date
    Dim lRow As Long

    'Create the worksheet objects
    Dim ws As Excel.Worksheet
    Set ws = Application.ActiveSheet

    Dim wsTarget As Excel.Worksheet
    Set wsTarget = ActiveWorkbook.Sheets("Sheet3")

    'Get the start and end.
    StartD = ws.Range("C5")
    EndD = ws.Range("C6")

    'Loop through and put the dates on the target sheet
    For lRow = 1 To (EndD - StartD)
        wsTarget.Range("C" & lRow) = StartD + lRow - 1
    Next lRow

    'Put the end date on the target sheet.
    wsTarget.Range("C" & lRow) = EndD
End Sub

答案 2 :(得分:0)

此刻您的代码确实显示了开始日期,但未显示结束日期。我在你的For循环中添加了+ 1,以便它将获得结束日期。我已经更改了代码,将日期从B2开始,如上所述。

Sub returnDates()
Dim StartD As Date, EndD As Date
StartD = Cells(5, 3)
EndD = Cells(6, 3)
For Row = 1 To (EndD - StartD) + 1
    Sheet3.Cells(Row + 1, 2) = StartD + Row - 1
Next Row
End Sub

请注意,从技术上讲,使用不带尺寸的变量/声明它是不好的做法。您正在使用Row,这可能是一个保留名称,这就是为什么它不会抱怨。另请注意,如果您想使用其他工作表,请将sheet3视为活动工作表,请告知我。我将修改以适应它。