简体   繁体   English

基于当前年份的动态下拉列表 Excel 和 VBA

[英]Dynamic dropdown based on the current year in Excel with VBA

Is it possible to create a dynamic drop down list based on the current year?是否可以根据当前年份创建动态下拉列表? For example, I want to create a dropdown based on the current year (2019);例如,我想根据当前年份(2019)创建一个下拉列表; which have 5 options:其中有 5 个选项:

  • 2019 2019
  • 2020 2020
  • 2021 2021
  • 2022 2022
  • 2023 2023

Then, starting 1/1/2020, the dropdown would automatically update to 2020, 2021, 2022, 2023, and 2024. Is this possible to do with some expression in the data validation drop down?然后,从 2020 年 1 月 1 日开始,下拉列表将自动更新为 2020、2021、2022、2023 和 2024。这可能与数据验证下拉列表中的某些表达式有关吗?

"Dynamic" validation in VBA could be achieved through rewriting the validation every time, when it is needed. VBA 中的“动态”验证可以通过每次在需要时重写验证来实现。 In the worse case, it could be every time the worksheet is opened or even every time when a selection is changed, probably through events.在更糟糕的情况下,可能是每次打开工作表时,甚至可能是每次更改选择时,可能是通过事件。

The validation in excel is could be list and in VBA this list is passed as a string separated with commas. excel 中的验证可以是列表,在 VBA 中,此列表作为用逗号分隔的字符串传递。 Thus, the string 2019, 2020, 2021, 2022, 2023 is quite a good example of the expected list.因此,字符串2019, 2020, 2021, 2022, 2023是预期列表的一个很好的例子。 There are different ways to do it, probably with a loop would be the "fanciest one", but as far as the values are only 5, then writing them manually is probably suitable as well.有不同的方法可以做到这一点,循环可能是“最奇特的”,但只要值只有 5,那么手动编写它们也可能是合适的。

TL DR - run this in a Workbook_Open() event: TL DR - 在Workbook_Open()事件中运行它:

Sub TestMe()

    Dim validationString As String
    validationString = Year(Now()) & ", " _
                    & Year(Now()) + 1 & ", " _
                    & Year(Now()) + 2 & ", " _
                    & Year(Now()) + 3 & ", " _
                    & Year(Now()) + 4

    With Worksheets(1).Cells(1, "A").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
                        Operator:=xlBetween, _
                        Formula1:=validationString
    End With

End Sub

在此处输入图像描述

Place these formulas in two separate tables without headers & starting in row 1将这些公式放在两个单独的表格中,没有标题并从第 1 行开始

Year:年:

=YEAR(TODAY())+ROW()-1

Month column 1:月份第 1 列:

=SWITCH([@Column2],1,"Jan",2,"Feb",3,"Mar",4,"Apr",5,"May",6,"Jun",7,"Jul",8,"Aug",9,"Sep",10,"Oct",11,"Nov",12,"Dec")

and column 2:和第 2 列:

=MONTH(DATE(YEAR(TODAY()),MONTH(TODAY())+ROW()-1,DAY(TODAY())))

..and you'll get dynamic references that start from current date ..您将获得从当前日期开始的动态引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM