【问题标题】:How to make a conditional dropdown base on cell values using VBA in Excel如何在 Excel 中使用 VBA 根据单元格值进行条件下拉
【发布时间】:2017-02-27 10:12:25
【问题描述】:

我正在尝试在 Excel 2016 中制作下拉菜单,但由于不经常使用,我现在不知道如何操作。

数据如下:

我正在尝试创建一个下拉列表,其中将包含基于 E 列单元格值的“Title 1”、“Title2”、“Title3”的值。

换句话说,是这样的:

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

实现这一目标的最佳方法是什么?我可以使用excel函数还是需要VBA?如果需要 VBA,任何提示将不胜感激。

【问题讨论】:

  • 您正在编写 "基于 D 列单元格值。" 并且您的伪代码实际上使用了一些 Cell D 但它会将其与您的链接图像在“E”列中显示的“索引”。请澄清
  • 对不起,我是说E栏
  • 然后相应地编辑您的问题
  • 完成!谢谢你告诉我!
  • 不客气。您尝试过发布的解决方案吗?

标签: vba excel dropdown


【解决方案1】:

如果您正在处理 excel UI 中的下拉单元格,那么您可以使用此代码(请参阅 cmets 以根据您的实际需要对其进行调整):

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

【讨论】:

    【解决方案2】:

    使用 VBA,这样的事情可能会奏效。组合框应该在表单中,数据应该在名为“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
    

    【讨论】:

      猜你喜欢
      • 2020-07-24
      • 2015-10-29
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 2022-01-24
      相关资源
      最近更新 更多