Excel组合框列表

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

我在Excel中做汽车制造商列表,我有组合框的问题。我从D2列填充我的组合框。

  • 美国
  • 美国
  • 日本
  • 德国
  • 法国

例如美国有很多汽车公司,但我想在我的组合框中只展示一次美国。现在美国在组合框中显示2次,因为它是在D2列中写的。有没有简单的方法修改Excel或编写VBA,以便每个国家只在组合框中显示一次。请帮助我很困惑。

请看下面的图片。

excel vba excel-vba
1个回答
0
投票

代码将放入standard module,可以通过VBE添加(Alt + F11)

选项1使用字典收集独特的国家

Option Explicit

Public Sub PopulateCombo()

    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Sheet2") 'change as appropriate

    Dim lastRowInD As Long
    Dim dedupRange As Range

    lastRowInD = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row
    Set dedupRange = ws.Range("D2:D" & lastRowInD)

    Dim dict As New Scripting.Dictionary
    Dim currCell As Range

    For Each currCell In dedupRange
         If Not dict.Exists(currCell.Value2) Then dict.Add currCell.Value2, currCell.Value2
    Next currCell

    Dim key As Variant

    With ws.OLEObjects("ComboBox1").Object
        .Clear
        For Each key In dict.Keys
            .AddItem dict(key)
        Next key

    End With

End Sub

选项2:使用重复数据删除Excel功能。

警告:这将从D列的工作表中删除重复项。

如果您在工作表中有一个ActiveX comboxbox,并且名为Countries的命名区域由Ctrl + F3创建以打开Name Manager然后输入

名称:国家

指:=OFFSET(Sheet2!$D$2,0,0,COUNTA(Sheet2!$D$2:$D$1048576),1)

如果您有早期版本的Excel,行数限制为65536,请调整$ D $ 1048576。

Public Sub PopulateCombo()

    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Sheet2") 'change as appropriate

    Dim lastRowInD As Long
    Dim dedupRange As Range

    lastRowInD = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row
    Set dedupRange = ws.Range("D2:D" & lastRowInD)

    dedupRange.RemoveDuplicates Columns:=1, Header:=xlNo

    With ws.OLEObjects("ComboBox1").Object
       .List = ws.Range("Countries").Value
    End With

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