2013-04-24 73 views
1

我剛剛在VBA中編程,我嘗試使用Excel工作表中的列表驗證數據。問題是每次從下拉列表中選擇不同的標準時,列表的大小都會有所不同。在VBA中使用動態列表驗證

例如:當我選擇中國時,列表變成10個不同的賣家。範圍A1到A10,但是當我選擇日本時,我只有5個賣家,從A1到A5。

所以我需要一個新的範圍在Formula1部分每次。

With Selection.Validation 
    .Delete 
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ 
    xlBetween, Formula1:="=$Z$1:$Z$30" 
    .IgnoreBlank = True 
    .InCellDropdown = True 
    .InputTitle = "" 
    .ErrorTitle = "" 
    .InputMessage = "" 
    .ErrorMessage = "" 
    .ShowInput = True 
    .ShowError = True 
End With 

什麼是最好的方法來做到這一點?

我知道如果我離開一個固定的範圍它可以工作,但它看起來不好,因爲它留下了很多空的空間,它看起來不整齊。

我希望這是可以理解的。

回答

1

你可以得到列的東西拉斯維加斯非空單元格這樣

Worksheets("Sheet1").Range("A1").End(xlDown) 

然後你只需從A1建立自己的一級方程式性能結果。

Dim strFormula1 as string 
strFormula1 = "=$A$1:" & Worksheets("Sheet1").Range("A1").End(xlDown).Address() 

希望它能幫助,沒有測試可能有錯誤

0

其他兩個答案是簡單的,但如果你有需要在驗證非連續非空白單元格將無法正常工作名單。這種方法應該克服:)

你可以在VBA中使用自定義函數來返回過濾後的字符串地址。這將返回過濾後的地址,否則將返回原始地址如果過濾後的地址不是有效範圍。

注意如果返回的地址超過255個字符的限制,這可能會失敗。

With Selection.Validation 
.Delete 
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ 
xlBetween, Formula1:=GetAddress(Range("$Z$1:$Z$30")) 
.IgnoreBlank = True 
.InCellDropdown = True 
.InputTitle = "" 
.ErrorTitle = "" 
.InputMessage = "" 
.ErrorMessage = "" 
.ShowInput = True 
.ShowError = True 
End With 

將函數放在一個普通的代碼模塊中。

Function GetAddress(myRange As Range) As String 

Dim cl As Range 
Dim c As Long: c = 1 
Dim tmpAddress As String 

For Each cl In myRange 
    If cl.Value <> vbNullString Then 
     'Create a string value of cell address matching criteria' 
     If tmpAddress = vbNullString Then 
      tmpAddress = myRange.Cells(c).Address 
     Else: 
      tmpAddress = tmpAddress & "," & myRange.Cells(c).Address 
     End If 
    End If 
    c = c + 1 
Next 

If Not Range(tmpAddress) Is Nothing Then 
    GetAddress = "=" & tmpAddress 
Else: 
    MsgBox "There are no non-empty cells in this range.", vbInformation 
    GetAddress = "=" & myRange.Address 
End If 

End Function 
+0

我相信你的答案完美無瑕,但它爲我提高:) – Pietro 2013-04-24 20:15:11

+0

沒問題。這種方法唯一可以做到的,其他人不能做的是,它允許你的範圍在任何地方包含空白單元格。其他方法*要求*範圍在第一個空白單元處結束。如果這是你的問題的程度,那麼其他答案是完全可以接受的。乾杯! – 2013-04-24 20:18:05

+0

在我的情況下,我不會遇到這個問題,但我會爲您的未來留下您的想法。 Thnx再次。 – Pietro 2013-04-24 20:41:32

1

使用命名的範圍與式

要創建一個名稱去公式/名稱管理器/新

的choise的名稱,例如資料驗證,在引用關聯使用

=OFFSET(Sheet1!$Z$1,0,0,COUNTA(Sheet1!$Z:$Z),1) 

現在,你有一個動態的時間間隔,並可以用於你的驗證。