在特定日期范围之间打印周数

时间:2016-07-12 16:34:34

标签: vba excel-vba excel

我的Excel工作表中有数据可以通过此功能复制:

sub dummy_data

    start_date = Sheets("Blad1").Cells(2, 4) = "20-03-2014"
    end_date = Sheets("Blad1").Cells(3, 4) = 20-04-2014"

End sub

现在我想创建一个这些日期之间所有周的列表。因此我做了:

Sub print_dates

  start_date = Sheets("Blad1").Cells(2, 4)
  end_date = Sheets("Blad1").Cells(3, 4)

  'Get number of weeks
    r = (end_date - start_date) / 7
    r = Round(r)

  new_date = start_date
  counter = 0

  While (new_date < (end_date - 7))

   For i = 1 To r

       counter = counter + 7
       new_date = start_date + counter

  'print date
      Sheets("Blad1").Cells(i, 4).FormulaLocal = new_date
  Next i
Wend

End sub

但这有点作用,但它总是给我一行太多。所以,如果我 输入start_date = 23-3-2013和end_date 04-04-2013我在04-04-2013之后得到一个值。

关于我如何只能在一定范围之间进行概述的任何想法?

3 个答案:

答案 0 :(得分:0)

问题是For Loop内的While Loop

那就是说,我刚刚测试了这段代码,它运行起来更简单。

Sub print_dates()

  start_date = Sheets("Blad1").Cells(2, 4)
  end_date = Sheets("Blad1").Cells(3, 4)

  new_date = start_date

  i = 1

  While (new_date < (end_date - 7))

    new_date = new_date + 7

    'print date
    Sheets("Blad1").Cells(i, 5).FormulaLocal = new_date

    i = i + 1

   Wend

End Sub

答案 1 :(得分:0)

尝试以下代码:

Sub print_dates()

start_date = Sheets("Blad1").Cells(2, 4)
end_date = Sheets("Blad1").Cells(3, 4)

'Get number of weeks
r = (end_date - start_date) / 7
r = Round(r)

new_date = start_date
counter = 0
For i = 1 To r
    If new_date + 7 <= end_date Then
        counter = counter + 7
        new_date = start_date + counter

        'print date
        Sheets("Blad1").Cells(i, 5).FormulaLocal = new_date

    End If
Next i

End Sub

答案 2 :(得分:0)

尝试使用datediff确定多少周。更容易。 MSDN has a really good datediff function tutorial here

R = DateDiff("w", startdate, enddate) ' Determine week difference between two dates.

此外,我怀疑额外的一周被添加,因为代码在星期日的第一天,而不是星期一。所以你还必须考虑当天和vbsunday之间的日子。或者只是把它放在这样的约会函数中。

R = DateDiff("w", startdate, enddate, vbmonday or whatever current day.)