2014-01-15 75 views
0

我想用兩個不同的動態驗證列表填充兩個單元格。第一個是字符串數組,第二個是日期數組。在動態驗證列表中填充唯一日期

我正在使用以下代碼。

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 

通過 子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

我在創造valseries的獨特價值時犯了一些錯誤。聲明valseries爲Variant作品。聲明valseries爲Date不起作用。無論如何感謝您的意見。

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 
+0

的例子,在看看非常感謝。除了強制使用日期格式之外,它與連接完全相同。正如我發佈的那樣,這個錯誤在別的地方。 – Peekay