2017-02-27 257 views
0

我试图在Excel 2016中创建下拉列表,但由于不经常使用它,因此我现在不会如何操作。如何使用Excel中的VBA使用单元格值进行条件下拉列表

的数据是这样的:

Excel data screenshot

我想创建一个将包含“标题1”的值的下拉列表中,“标题2”,“TITLE3”基于E列的单元格值。

换句话说,这样的事情:

if Cell E == 'index' 
    add Cell A value to dropdown 
end 

什么是完成这一任务的最好方法是什么?我可以使用Excel功能吗?还是我需要VBA?如果需要VBA,任何提示将不胜感激。

+0

你写_“的基础D列的单元格值“。_和您的伪代码实际上使用了一些_Cell D_,但它将它与链接的图像在列”E“中显示的索引进行比较。请澄清 – user3598756

+0

对不起,我的意思是E栏 – Jeremie

+0

然后编辑你的问题 – user3598756

回答

0

,如果你正在处理在Excel UI下拉单元格,然后你可以使用此代码(见注释将其调整到您的实际需求):

Sub Main() 
    With Worksheets("sheetWithDropDownName").Range("A1").Validation '<--| change "sheetWithDropDownName" and "A1" to your actual "dropdown" worksheet and cell references 
     .Delete 
     .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ 
     xlBetween, Formula1:=Join(GetTitles(), ",") 
     .IgnoreBlank = True 
     .InCellDropdown = True 
     .InputTitle = "" 
     .ErrorTitle = "" 
     .InputMessage = "" 
     .ErrorMessage = "" 
     .ShowInput = True 
     .ShowError = True 
    End With 
End Sub 

Function GetTitles() As Variant 
    Dim cell As Range, rng As Range 

    With Worksheets("sheetWithDataName") '<--| change "sheetWithDataName" to your actual sheet with data name 
     Set rng = .Range("A1", .cells(.Rows.Count, "E").End(xlUp)) '<--| set a range as its columns A:E range from row 1 down to last column E not empty row 
    End With 
    With CreateObject("Scripting.Dictionary") 
     For Each cell In rng.Columns(5).cells 
      If cell.Value = "index" Then .Item(cell.Offset(, -4).Value) = cell.Offset(, -4).Value 
     Next cell 
     GetTitles = .keys 
    End With 
End Function 
+0

太棒了!它完美的作品! – Jeremie

0

使用VBA,这样的事情可能会起作用。 Combobox应该放在表单中,数据被放在名为“MyData”的表格中。

Private Sub UserForm_Initialize() 
Dim lLastRow As Long 
Dim i As Integer 

lLastRow = Worksheets("MyData").Cells(Rows.Count, 1).End(xlUp).Row 

    For i = 2 To lLastRow 
     If Worksheets("MyData").Cells(i, 5) = "index" Then 
      ComboBox1.AddItem (Worksheets("MyData").Cells(i, 1)) 
     End If 
    Next 

End Sub 
相关问题