【问题标题】:Loop through date range with a monthly step以每月步骤循环遍历日期范围
【发布时间】:2021-12-30 01:16:46
【问题描述】:

我在使用 VBA 时遇到问题,我正在尝试以每月步长循环进入日期范围,但我在“每月步长”部分苦苦挣扎。

其实我可以得到这个输出:

13/08/2021 
14/08/2021 
15/08/2021 
16/08/2021 
17/08/2021 
18/08/2021

而我想要得到的更像是:

08/2021 
09/2021 
10/2021 
11/2021 
12/2021 
01/2022 

这是我的代码:

aIndex = 1
    For Each Cell In Range("F2", Range("F2").End(xlDown))
            aIndex = aIndex + 1
            For J = Range("D" & aIndex) To Cell
                Debug.Print J
            Next J

    Next Cell

“F”和“D”列只包含格式为“DD/MM/YYYY”的日期,我在“D”和“F”日期之间循环。

提前致谢,

尼古拉斯。

【问题讨论】:

  • Debug.Print Format$(J, "mm/yyyy")
  • 感谢braX,但我只想要“08/2021”的 1 个输出,而不是每天一个。这是实际输出:``` 07/2021 07/2021 08/2021 08/2021 08/2021 08/2021 08/2021 ```
  • 从最小日期的月份和年份到最大日期的月份和年份进行for next循环

标签: vba date for-loop


【解决方案1】:

有很多方法可以做到这一点,但尽量保持与你所拥有的相似,删除不需要的东西,并改用字典:

Sub test()
  Dim sDate As String
  Dim dict As Object
  Dim Cell As Range

  Set dict = CreateObject("Scripting.Dictionary")

  For Each Cell In Range("F2", Range("F2").End(xlDown))
     sDate = Format$(Range("D" & Cell.Row), "mm/yyyy")
     If Not dict.Exists(sDate) Then
       dict.Add sDate, 1
       Debug.Print sDate
     End If
  Next

  Debug.Print "Total: " & dict.Count

End Sub

如果您的 Debug.Print 不是您所需要的,您可以在之后使用 Dictionary 进行一些操作。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-01-10
  • 2010-12-23
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 2011-02-19
  • 2020-03-06
相关资源
最近更新 更多