vba - Excel VBA for 循环条件

标签 vba excel

我想问一下VBA中的for循环, 我有下面的脚本来提醒我(“提醒”是一个子功能)如果当前日期是 CheckDate1,2,3,4,5,6... 我想问一下,如果我需要添加更多日期,我可以使用 for 循环来包含所有 CheckDate(s) 而不是添加更多 ElseIf 函数吗?

抱歉我的英语不好,非常感谢!

Dim dtmMyDate As Date

Const CheckDate1 = #1/9/2018#
Const CheckDate2 = #1/11/2018#
Const CheckDate3 = #1/16/2018#
Const CheckDate4 = #1/18/2018#
Const CheckDate5 = #1/23/2018#
Const CheckDate6 = #1/25/2018#

dtmMyDate = DateSerial(Year(Now()), Month(Now()), Day(Now()))
If dtmMyDate = CheckDate1 Then
    Remind
ElseIf dtmMyDate = CheckDate2 Then
    Remind
ElseIf dtmMyDate = CheckDate3 Then
    Remind
ElseIf dtmMyDate = CheckDate4 Then
    Remind
ElseIf dtmMyDate = CheckDate5 Then
    Remind
ElseIf dtmMyDate = CheckDate6 Then
    Remind
Else
    NormalCheck
End If

最佳答案

做这样的事情会更可持续:

将日期加载到工作表上的 Excel 范围中,并 Define a Dynamic Named Range例如,MyDates 并在工作簿级别分配范围。这样添加或删除日期将非常容易。

那么这可以是您的代码:

Dim vDates as Variant
vDates = Range("myDates")

Dim lDate as Long

For lDate = LBound(vDates) to UBound(vDates)
    If vDates(lDate,1) = Format(Now,"m/d/yyyy") Then 
        Remind
        Dim bRemind as Boolean
        bRemind = True
        Exit For
    End If
Next

If Not bRemind Then NormalCheck

关于vba - Excel VBA for 循环条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45703824/

相关文章:

vba - 什么时候VBA中的两个对象相同?

excel - 保存原件副本时另存为错误

python - 如何使用 python 和 Django 高效导出大型 Excel 文件

excel - 宏调用将针对工作簿中所有打开的工作表运行的函数

excel - 如何从Excel中的给定列中随机选择值

vba - 更改 Word 中的样式

arrays - 使用数组使用 VBA for Excel 获取 HTML 表格内容

vba - 使用 Excel VBA 将单个工作簿拆分为包含多个工作表的多个工作簿

c# - 使用带有 C# 的 OpenXML 在 Excel 文档中将文本对齐设置为居中

VBA宏从两个日期列中减去工作日