【问题标题】:EXCEL VBA - Do While loop with 2 datesEXCEL VBA - 使用 2 个日期执行 While 循环
【发布时间】:2017-07-12 16:24:31
【问题描述】:

正在使用开始日期和当前日期之间的日期在 Excel 中填充一行。人口是每周一次,以下是我所做的功能。它可以正常工作,直到它不会停止但会继续无限运行,直到出现溢出错误,因此我的假设是 CurrentDate 无法正常工作。

使用的 2 个日期是 StartDate = 04/1/2016CurrentDate = 12/07/2017

任何帮助或建议将不胜感激。

Public Function PopulateStartOfWeekDates()

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")

    Dim StartDate As Date
    Dim CurrentDate As Date
    StartDate = FirstMondayOfYear()
    CurrentDate = Date

    Dim WeekOffset As Integer
    Dim i As Integer
    i = 12
    WeekOffset = 0

    Debug.Print StartDate
    Debug.Print CurrentDate

    Do While StartDate < CurrentDate        
        wsCRC.Cells(5, i) = StartDate + WeekOffset
        wsCRC.Cells(5, i).EntireColumn.AutoFit
        i = i + 1
        WeekOffset = WeekOffset + 7                    
    Loop

End Function

【问题讨论】:

  • 你需要分享你的FirstMondayOfYear函数,在调试模式下运行时StartDate有什么价值?
  • StartDate 在循环中保持不变,除非我弄错了?
  • 另外,你在哪里增加循环 StartDate 内的值 Do While StartDate &lt; CurrentDate ?你不是要在最后加上StartDate = StartDate +7吗?

标签: vba excel


【解决方案1】:

如果您决定需要维护 StartDate 的值(例如,稍后在代码中使用),您可以将循环替换为:

i = 0
Do While StartDate + i * 7 < CurrentDate
    wsCRC.Cells(5, i + 12) = StartDate + i * 7
    wsCRC.Cells(5, i + 12).EntireColumn.AutoFit
    i = i + 1
Loop

【讨论】:

  • 这是个好主意,请记住这一点,因为它看起来确实很有用,但我使用另一个函数来获取开始日期,所以我现在不需要特别执行此操作
【解决方案2】:

我自己看了这个之后,我意识到我没有增加开始日期,因此循环是无限的。感谢@Nathan_Sav 在 cmets 中也指出了这一点。

【讨论】:

  • 工作时我总是在wendloop 等处添加断点,以防万一:)
猜你喜欢
  • 1970-01-01
  • 2017-04-01
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 2018-01-16
相关资源
最近更新 更多