在另一个工作表上创建列表 - 运行时错误9

时间:2017-10-04 15:49:35

标签: excel vba excel-vba

我正在使用以下从another post编辑的代码列出开始日期和结束日期之间的所有日期。该列表是在与包含开始日期和结束日期的单元格不同的工作表上创建的。如果我打开了sheet6,代码就可以工作,但如果我在sheet1上则不行。我得到一个'运行时错误9:下标超出范围。'调试突出显示对sheet6的引用。无论活动表如何,我如何修改此代码?

Sub GenerateDates()

Dim FirstDate As Date
Dim LastDate As Date
Dim NextDate As Date

FirstDate = Sheet1.Range("CZ").Value
LastDate = Sheet1.Range("DA").Value

NextDate = FirstDate
Worksheets("sheet6").Range("A1").Select
Do Until NextDate > LastDate

    ActiveCell.Value = NextDate
    ActiveCell.Offset(1, 0).Select
    NextDate = NextDate + 1

Loop

End Sub

1 个答案:

答案 0 :(得分:1)

基本上,总是尝试设置并完全限定工作表和范围变量。然后直接使用它们而不是使用Select / Activate。

Sub GenerateDates()

    Dim wb As Workbook
    Dim wsData As Worksheet
    Dim wsDest As Worksheet
    Dim rDest As Range
    Dim FirstDate As Date
    Dim LastDate As Date
    Dim NextDate As Date

    Set wb = ActiveWorkbook
    Set wsData = wb.Sheets(1)
    Set wsDest = wb.Sheets(6)
    Set rDest = wsDest.Range("A1")

    FirstDate = wsData.Range("CZ").Value
    LastDate = wsData.Range("DA").Value
    NextDate = FirstDate

    Do Until NextDate > LastDate
        rDest.Value = NextDate
        Set rDest = rDest.Offset(1)
        NextDate = NextDate + 1
    Loop

End Sub