我在列中有一个日期列表。我想在用户表单上添加一个组合框,从那些日期开始,它们就是唯一的年份。
userform用于根据用户选择的月份和年份生成报告。我只想要几年就有条目。因此,当它进入2014年时,第一个条目进入2014年的电子表格,可以选择报告生成器。
Dim c As Range, Coll As New Collection
On Error Resume Next
For Each c In Sheets("Permits & Access").Range(ActiveSheet.Range("L3"), Sheet.Range ("L3").End(xlDown))
Coll.Add c.Value, c.Value
Next c
On Error GoTo 0
For Each Item In Coll
cboYear.AddItem Item
Next Item
这是我用来显示唯一日期的代码段。但实际上我只需要独特的岁月。我知道使用Year()方法来提取年份,只是没有运气实现它。
答案 0 :(得分:0)
这是我如何做的,而是使用Dictionary
代替。
Option Explicit
Private Sub UserForm_Initialize()
Dim dict As Object, item As Variant
Dim cel, rng As Range
Set dict = CreateObject("scripting.dictionary")
Set rng = ThisWorkbook.Sheets("Sheet1").Range("A2:A12")
'--> empty ComboBox1
Me.ComboBox1.Value = ""
'--> sort the range, sorting Collection or Dictionary is a bit complex
rng.Sort Key1:=rng.Cells(1), Order1:=xlAscending, Header:=xlNo, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
'--> Test for unique year, add to dictionary
For Each cel In rng
If Not dict.exists(Format(cel, "yyyy")) Then
dict.Add Format(cel, "yyyy"), Format(cel, "yyyy")
End If
Next
'--> Populate ComboBox1 with the unique year
For Each item In dict.items
Me.ComboBox1.AddItem item
Next
Set dict = Nothing
Set rng = Nothing
End Sub
希望这对你有所帮助。