【问题标题】:I need to populate a combobox based on a column on a worksheet我需要根据工作表上的列填充组合框
【发布时间】:2021-09-20 02:07:15
【问题描述】:

我在用户窗体上有一个组合框,该组合框当前由表中的列填充。 Column A 此列有一个工具编号,其中两个数字可以完全相同,除了末尾的字母。 (例如单元格 A5 和 A6)如何填充组合框以使其仅包含该数字的最新版本?

【问题讨论】:

  • 你已经尝试了什么?您的代码的哪一部分不起作用?请编辑您的问题以提供此信息,您获得帮助的机会成倍增加。请看stackoverflow.com/help/how-to-ask

标签: excel vba combobox


【解决方案1】:

通过扭曲填充独特的组合框

  • 调整第一个单元格地址、工作表和组合框。
Option Explicit

Sub PopulateComboUnique()
    
    Const First As String = "A2"
    
    Dim rg As Range: Set rg = RefColumn(Sheet1.Range(First))
    If rg Is Nothing Then Exit Sub ' empty column range
    
    Dim sData As Variant: sData = GetColumnRange(rg)
    
    Dim dData As Variant: dData = ArrUniqueSpecial(sData)
    If IsEmpty(dData) Then Exit Sub ' no unique values
        
    Sheet1.ComboBox1.List = dData
    
'    Dim n As Long
'    For n = LBound(dData) To UBound(dData)
'        Debug.Print dData(n)
'    Next n
        
End Sub

Function RefColumn( _
    ByVal FirstCellRange As Range) _
As Range
    If FirstCellRange Is Nothing Then Exit Function
    With FirstCellRange.Cells(1)
        Dim lCell As Range
        Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
            .Find("*", , xlFormulas, , , xlPrevious)
        If lCell Is Nothing Then Exit Function
        Set RefColumn = .Resize(lCell.Row - .Row + 1)
    End With
End Function

Function GetColumnRange( _
    ByVal rg As Range) _
As Variant
    If rg Is Nothing Then Exit Function
    Dim cData As Variant
    With rg.Columns(1)
        If .Rows.Count = 1 Then
            ReDim cData(1 To 1, 1 To 1): cData(1, 1) = .Value
        Else
            cData = .Value
        End If
    End With
    GetColumnRange = cData
End Function

Function ArrUniqueSpecial( _
    ByVal sData As Variant) _
As Variant
    If IsEmpty(sData) Then Exit Function
   
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare
    
    Dim Key As Variant
    Dim r As Long
    
    For r = 1 To UBound(sData, 1)
        Key = sData(r, 1)
        If Not IsError(Key) Then
            If Len(Key) > 1 Then ' not allowing zero or one character
                dict(Left(Key, Len(Key) - 1)) = Right(Key, 1)
            End If
        End If
    Next r
    If dict.Count = 0 Then Exit Function
    
    Dim dData() As String: ReDim dData(1 To dict.Count)
    
    r = 0
    For Each Key In dict.Keys
        r = r + 1
        dData(r) = Key & dict(Key)
    Next Key

    ArrUniqueSpecial = dData
End Function

【讨论】:

  • 在userform初始化下调用sub吗?
  • 当然,如果您希望在初始化用户表单时填充这些值。
  • 嘿,我收到一条错误消息,指出“对象不支持此属性或方法”。我运行了调试器,问题似乎来自 Sheet1.ComboBox1.List = dData 代码行。我正在用户窗体上填充一个组合框。我将如何重写它以使用用户表单?
  • 没关系。我是个白痴,忘了我更改了用户表单名称。
猜你喜欢
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
相关资源
最近更新 更多