【问题标题】:Populating a ComboBox with a Dynamic Range in a single column在单列中填充具有动态范围的组合框
【发布时间】:2021-09-23 13:47:26
【问题描述】:

我在 excel 中创建一个用户表单,其中我有一个搜索框,用于搜索 A 列中的所有值。在搜索框中选择值时。我想提取与 A 列中的值相关的所有可能值。例如.... 在要提取项目编号的组合框中。当此人选择 LR UK 1 时,我希望项目编号组合框可以选择 1 或 2....

问题是我的代码只通过了 2 的值。我可以理解为什么我的代码会通过它所做的事情,但是我正在努力让它通过项目对应列中的所有值名称范围。

Private Sub Find_Click()

Dim searchRange As Range
Dim foundCell As Range
Dim mysearch As String
    
mysearch = CBProjName.Value

With Sheets("Records")
    Set searchRange = Sheets("Records").Range("A2", .Range("A" & .Rows.Count).End(xlUp))
End With

Set foundCell = searchRange.Find(what:=mysearch, Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not foundCell Is Nothing Then
    TBCaseNumber = foundCell.Offset(0, 1).Value
    CBProjNumbers.Value = foundCell.Offset(0, 2).Value 'this is the val that only displays 2
            
Else
     MsgBox "Uh oh, things have gone a little sideways and the project " & CBProjName.Value & " cannot be located. Please try another Project!"
End If

End Sub

【问题讨论】:

    标签: excel vba range


    【解决方案1】:

    您应该做的是遍历数据并获取所选项目的所有项目编号。

    为了加快速度,我们可以将所有数据放在一个数组中并循环遍历。

    Option Explicit
    
    Private Sub Find_Click()
    Dim arrData As Variant
    Dim arrProjectNos As Variant
    Dim mysearch As String
    Dim cnt As Long
    Dim idx As Long
        
        If CBProjName.ListIndex <> -1 Then
            mysearch = CBProjName.Value
        
            With Sheets("Records")
                Set searchRange = Sheets("Records").Range("A2", .Range("A" & .Rows.Count).End(xlUp))
            End With
        
            arrData = searchRange.Resize(, 3).Value
        
            ReDim arrProjectNos(1 To UBound(arrData, 1))
            
            For idx = LBound(arrData, 1) To UBound(arrData, 1)
                If arrData(idx, 1) = mysearch Then
                    TBCaseNumber = arrData(idx, 2)
                    cnt = cnt + 1
                    arrProjectNos(cnt) = arrData(idx, 3)
                End If
            Next idx
            
            If cnt > 0 Then
                ReDim Preserve arrProjectNos(1 To cnt)
                CBProjNumbers.List = arrProjectNos
            Else
                MsgBox "Uh oh, things have gone a little sideways and the project " & mysearch & " cannot be located. Please try another Project!"
            End If
        Else
            MsgBox "Please select a project to search for!"
        End If
        
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      相关资源
      最近更新 更多