2015-07-20 38 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

相關問題