从表中选择符合条件的数据,将其添加到用户窗体中的组合框

问题描述 投票:0回答:1

我有一个 Excel 数据表。使用 VBA 我想从表 (Active_Accessions) 的第一列中选择与第二列中的名称位于同一行的值(数字)。这些名称与组合框中的名称 (cmbxLatinName) 相匹配。然后,所有这些的结果应该将第 1 列中选定的数字列表添加到不同的 ComboBox (cmbxSourceAcc) 中。

这段代码看起来不错,除了

Datarw
,我不能
Dim
它。我知道有一种方法可以直接进入组合框,但这太复杂了,所以我打算将结果写入表的第三列,在那里我知道如何将它们拉入组合框。

'Match source accession to its sub-accession
Public Function GetSourceAcc()

    Dim Tbl As ListObject
    Dim r As Long
    Dim Datarw As
    
    Set Tbl = Sheet5.ListObjects("Active_Accessions")
    r = 1
    For Each Datarw In Tbl.ListRows
    If Datarw.ListColumns(2).DataBodyRange = Me.cmbxLatinName.Value Then
        Tbl.ListColumns(3).Offset(r, 0) = Tbl.ListColumns(1).Value
        r = r + 1
    End If
    Next
    
    GetSourceAcc = Sheet5.ListObjects("Active_Accessions").ListColumns(3).DataBodyRange.Value
    
    Let Me.cmbxSourceAcc.List = GetSourceAcc
    Me.cmbxSourceAcc.ListIndex = 0

End Function
excel vba combobox textmatching
1个回答
2
投票

用火柴填充组合框

Sub GetSourceAcc()
    ' It is assumed that the ranges have at least 2 cells (rows) (each).

    Dim tbl As ListObject: Set tbl = Sheet5.ListObjects("Active_Accessions")
    
    ' Source Lookup (sl)
    Dim slrg As Range: Set slrg = tbl.ListColumns(2).DataBodyRange
    Dim srIndexes(): srIndexes = Application.Match(Me.cmbxLatinName.List, slrg, 0)
    ' 'srIndexes' holds the matching row indexes i.e. the numbers of the rows
    ' where each item from the combo box was found in the source lookup range.
    ' If an item was not found, an error value was returned (shouldn't happen).
    
    ' Source Return (sr)
    Dim srData(): srData = tbl.ListColumns(1).DataBodyRange.Value
    
    ' Write the matching values to an array.
    
    ' Destination (d)
    Dim dCount As Long: dCount = UBound(srIndexes)
    Dim dArr(): ReDim dArr(1 To dCount)
    
    Dim d As Long, n As Long
    
    For d = 1 To dCount
        If IsNumeric(srIndexes(d, 1)) Then
            n = n + 1
            dArr(n) = srData(srIndexes(d, 1), 1)
        End If
    Next d
    
    If n < dCount Then ReDim Preserve dArr(1 To n)
    
    'Debug.Print Join(dArr, ", ")
    
    ' Return the matching values in another combo box.
    
    Me.cmbxSourceAcc.List = dArr
    Me.cmbxSourceAcc.ListIndex = 0

    MsgBox "Combo box populated.", vbInformation

End Function
© www.soinside.com 2019 - 2024. All rights reserved.