我正在尝试用两个不同的动态验证列表填充两个单元格。第一个是字符串数组,第二个是日期数组。
我正在使用以下代码。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("G21")) Is Nothing Then
Call getValidationSeries
End If
If Not Intersect(Target, Range("I21")) Is Nothing Then
Call getValidationExpiry
End If
End Sub
接下来是
Sub getValidationSeries()
Dim valseries(100) As String
~~~Other declarations
~~~~ code to fill identify unique values in valseries
Range("Charts!G21").Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=Join(valseries, ",")
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
和
Sub getValidationExpiry()
Dim valseries(100) As Date
~~~Other declarations
~~~~ code to fill identify unique dates in valseries
Range("Charts!I21").Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=Join(valseries, ",")
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
问题
上面的第一个子工作正常,其中valseries是一个字符串数组。但是当valseries是第二个子日期中的日期数组时,它不起作用。我知道我不能在第二个函数中使用Join,因为它是一个日期变量。当我将valseries声明为Variant而不是Date变量时,它可以工作,但它将所有日期转换为字符串。我需要它们作为日期(当然我可以将它们重新转换回日期,但那并不高效)
有任何线索吗?我不想将唯一值存储在一个范围内。
我查看了这些(与我为字符串所做的相似)但对日期没什么帮助。
Programmatically creating Excel VBA validation list
Excel Validation Drop Down list using VBA
Excel: How to create dynamic data validation list based on data table
提前致谢。
答案 0 :(得分:0)
我在创造valseries的独特价值时犯了一些错误。将valseries声明为Variant可以正常工作。声明valseries为Date不起作用。无论如何,感谢您的意见。
答案 1 :(得分:0)
以下是一个可以帮助您的简单工作示例:
Sub dural()
Dim DateArray(1 To 3) As Date
Dim str As String
DateArray(1) = DateSerial(2004, 12, 25)
DateArray(2) = DateSerial(1945, 1, 18)
DateArray(3) = DateSerial(2020, 7, 1)
For i = LBound(DateArray) To UBound(DateArray)
If str = "" Then
str = CStr(DateArray(i))
Else
str = str & "," & CStr(DateArray(i))
End If
Next i
ActiveCell.NumberFormat = "dd mmmm yyyy"
With ActiveCell.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=str
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub