【问题标题】:Combobox values from array are not shown in 2 columns数组中的组合框值未显示在 2 列中
【发布时间】:2021-08-16 01:54:46
【问题描述】:

我有一个奇怪的问题,我的组合框将数组的内容重叠显示,而不是显示在 2 列中。下图显示了结果:

我下面的代码基本上可以得到正确的结果,但我期望的结果应该是:

F106612 M2500 E4X GA

这是我的代码:

    Public Sub ComboBox4_DropButtonClick()

           If Range("AA1").Value = "RoutineCompleted" Then
  
           RunRoutine.Enabled = False

           Dim rCell As Range, ws As Worksheet, arr

           Set ws = Worksheets("Sheet1")
           ComboBox4.ColumnCount = 2

    With CreateObject("Scripting.Dictionary")
       For Each rCell In ws.Range("N3", ws.Cells(Rows.Count, "N").End(xlUp))
         If Not .Exists(rCell.Value) And rCell.Offset(0, -11).Value = 1 And rCell.Value <> "" Then
            .Add rCell, rCell.Offset(0, -3).Value 
       End If
    Next rCell
    arr = Application.Transpose(Array(.Keys, .items)) 

        End With

    With ComboBox4
       .ColumnCount = 2 'set number of columns to be shown
       .List = arr      'put the array in the list property
    End With

   End If


    End Sub

谁能指出我正确的方向?

谢谢

【问题讨论】:

  • arr = Application.Transpose(Array(.Keys, .items)) 这可能不会像您认为的那样做:它只是创建了一个数组数组。您需要遍历这两个数组并将它们组合成一个 2D 数组。
  • 谢谢蒂姆,老实说,我想做的就是在列中获取所有唯一值,并在第二列中显示其相关描述。哥们,我需要研究什么来解决这个问题?

标签: excel vba filter combobox


【解决方案1】:

未经测试:

Public Sub ComboBox4_DropButtonClick()

    Dim rCell As Range, ws As Worksheet, dict
    
    If Range("AA1").Value = "RoutineCompleted" Then
    
        RunRoutine.Enabled = False
        Set ws = Worksheets("Sheet1")
        ComboBox4.ColumnCount = 2
    
        Set dict = CreateObject("Scripting.Dictionary")
        
        For Each rCell In ws.Range("N3", ws.Cells(Rows.Count, "N").End(xlUp))
            If Not dict.Exists(rCell.Value) And _
                       rCell.Offset(0, -11).Value = 1 And _
                       rCell.Value <> "" Then
                dict.Add rCell, rCell.Offset(0, -3).Value
            End If
        Next rCell
        
        If dict.Count > 0 Then
            With ComboBox4
                .ColumnCount = 2 'set number of columns to be shown
                .List = DictToArray(dict)      'put the array in the list property
            End With
        Else
            '???
        End If
        
    End If 'routine completed
End Sub

'convert dictionary to 2D array
Function DictToArray(dict As Object)
    Dim arr, k, i As Long
    i = 0
    ReDim arr(0 To dict.Count - 1, 0 To 1)
    For Each k In dict.keys
        arr(i, 0) = k
        arr(i, 1) = dict(k)
        i = i + 1
    Next k
    DictToArray = arr
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    相关资源
    最近更新 更多