2015-07-20 39 views
0

我试图用工作表创建包含数据的组合框。我有这样做的代码,但我需要的是只显示给定列中的每个值之一。例如,在A列中,我有多条狗,猫和鱼,我想要的组合框显示的是3个列表,即狗,猫,鱼。如何让它停止显示狗,狗,狗,猫,猫,鱼,鱼,鱼,鱼等。以下是我目前使用的代码。使用工作表VBA中的每个值中只有一个值创建组合框Excel

With Worksheets("RuleID") 
    OriginatingDomainComboBox.List = .Range("A2:A" & .Range("A" & .Rows.Count).End(xlUp).row).value 
    End With 

任何帮助将是伟大的,如果有什么你可能需要现在让我知道。

感谢

回答

1

这里是完成这个任务的方法:

Public Sub loadValues() 
    Dim lastRow As Long 
    Dim rng As Excel.Range 
    Dim rawData As Variant 
    Dim columnItems() As String 
    Dim arraySize As Integer 
    Dim i As Long 
    Dim uniqueItems() As Variant 
    '------------------------------------------------------------------- 


    'Find data range 
    With Worksheets(1) 
     lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 
     Set rng = .Range(.Cells(1, 1), .Cells(lastRow, 1)) 
    End With 


    'Get data from worksheet. 
    rawData = rng '<-- for better performance we assign all the data to 
        ' Variant array and we iterate through this array 
        ' later instead of iterating through worksheet's cells 


    'Convert rawData array to 1D array of strings. 
    arraySize = UBound(rawData, 1) - LBound(rawData, 1) + 1 
    ReDim columnItems(1 To arraySize) 
    For i = LBound(columnItems) To UBound(columnItems) 
     columnItems(i) = rawData(i, 1) 
    Next i 


    'Get unique values from [columnItems] array by using function [uniqueValues]. 
    uniqueItems = uniqueValues(columnItems) 


    'Assign array of unique values as a list to ComboBox. 
    cmbTest.List = uniqueItems 


End Sub 

为了使这种方法正常工作,您需要包含function to get unique values from the given array

+0

你我的朋友是天才。非常感谢你做的这些。它的作用就像一种享受。你惊人的。谢谢:) :) @mielk – GBSingh

0

除了@ mielk的回答,你还可以使用字典来完成你所追求的。

下面使用'Microsoft Scripting Runtime'参考。请记住在工具 - >参考中启用它。

Option Explicit 
Sub populateUF() 
    Dim dict As Scripting.Dictionary, myItem As Variant 
    Dim lrow As Long, i As Long 
    Dim myValues() As Variant 

    Set dict = New Scripting.Dictionary 
    lrow = Cells(Rows.Count, 1).End(xlUp).Row 
    myValues = Range(Cells(2, 1), Cells(lrow, 1)) 
    For i = 1 To UBound(myValues, 1) 
     If Not dict.Exists("Item" & myValues(i, 1)) Then 
      dict.Item("Item" & myValues(i, 1)) = myValues(i, 1) 
     End If 
    Next i 

    For Each myItem In dict 
     UserForm1.ComboBox1.AddItem dict.Item(myItem) 
    Next myItem 

    UserForm1.Show 
End Sub 

我们使用.Existsmethod以评估是否从阵列的值已经预先被添加到词典中。新值将添加到字典中,从而只分配数组中的唯一值。然后我们使用for each语句遍历字典,将值赋给组合框。

要进一步阅读字典,请参见文档here,更详细地说,请参阅here

相关问题