2013-03-28 26 views
3

我現在有有一個表,看起來像這樣:Excel的過濾後的數據驗證列表上的單元格內容

| A |  B  | 
    +-------+-----------+ 
1 | State | City  | 
    +=======+===========+ 
2 | NSW | Goulburn | 
3 | NSW | Sydney | 
4 | VIC | Melbourne | 
5 | VIC | Horsham | 
6 | NSW | Tamworth | 

然後我還有一個表,看起來像這樣:

| A |  B  |  C  | 
    +-------+-----------+------------+ 
1 | State | City  | Other data | 
    +=======+===========+============+ 
2 |  |   |   | 

在這第二個表我已經將數據驗證應用於State和City列,並引用第一個表中的數據。所以我列出了所有州和城市的名單。

我希望能夠做的是,如果用戶在狀態欄中輸入「NSW」什麼,在城市列選項列表進行過濾,只顯示位於新南威爾士州

+0

使用'Worksheet_Change'事件動態地重新驗證的基礎上,在A列中 – 2013-03-28 01:11:47

+0

進入不知道如何寫這個劇本的價值? – McShaman 2013-04-02 21:33:09

+0

是的。見下面... – 2013-04-03 00:18:11

回答

1

廣場這個城市在工作表的代碼模塊中。

變化shTable的定義,指在其上您的查找表所在的工作表。

Private Sub Worksheet_Change(ByVal Target As Range) 
Dim myVal As String 
Dim cityList As String 
Dim table As Range 
Dim cl As Range 
Dim shTable As Worksheet: Set shTable = Sheets("Index") '<modify as needed' 

If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub 

myVal = Target.Value 
With shTable 
    Set table = .Range("A2", .Range("A2").End(xlDown)) 'contains your city/state table' 
End With 
    For Each cl In table 
    'Build a comma-separated list of matching cities in the state.' 
     If cl.Value = myVal Then 
      If cityList = vbNullString Then 
       cityList = cl.Offset(0, 1) 
      Else: 
       If InStr(1, cityList, cl.Offset(0,1).Value, vbBinaryCompare) > 0 Then 
       'avoid duplicates, but this is not a foolproof method.' 
       'probably should rewrite using an array or scripting dictionary' 
       'otherwise the possibility of partial match is a potential error.' 
        cityList = cityList & "," & cl.Offset(0, 1) 
       End If 
      End If 

     End If 
    Next 

'Now, with the cell next to the changed cell, remove ' 
' any existing validation, then add new validation ' 
' based on the cityList we compiled above. 
With Target.Offset(0, 1).Validation 
    .Delete 
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ 
    xlBetween, Formula1:=cityList 
    .IgnoreBlank = True 
    .InCellDropdown = True 
    .InputTitle = "" 
    .ErrorTitle = "" 
    .InputMessage = "" 
    .ErrorMessage = "" 
    .ShowInput = True 
    .ShowError = True 
End With 

End Sub 
+0

你是個天才大衛!兩個問題,在這裏很容易過濾任何重複?也有可能使用命名範圍,而不是靜態引用?如果是的話,語法是什麼? – McShaman 2013-04-03 02:40:35

+0

例如,如果你的表有一個連接到它的命名範圍,你可以做'Set table = .Range(「Named Range」)'(相應地更新)。我會更新答案以避免重複。 – 2013-04-03 02:45:46

+0

非常感謝大衛的幫助。我不得不將大於符號「>」更改爲等號「=」,但除此之外它完美地工作。我認爲我的下一步將解決如何在VBA中使用數組。但是這塊代碼在理解一些核心VBA概念方面變得非常有用。 – McShaman 2013-04-08 01:43:19

相關問題