Adicionar uma lista exclusiva de valores em uma caixa de combinação
Esses exemplos mostram diferentes abordagens sobre como obter uma lista de uma planilha e usá-la para preencher um controle de caixa de combinação usando apenas os valores exclusivos. O primeiro exemplo usa o método AdvancedFilter do objeto Range e o segundo usa o objeto Collection.
Código de exemplo fornecido por: Dennis Wallentin, VSTO & .NET & Excel
Sub Populate_Combobox_Worksheet()
'The Excel workbook and worksheets that contain the data, as well as the range placed on that data
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnData As Range
'Variant to contain the data to be placed in the combo box.
Dim vaData As Variant
'Initialize the Excel objects
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Sheet1")
'Set the range equal to the data, and then (temporarily) copy the unique values of that data to the L column.
With wsSheet
Set rnData = .Range(.Range("A1"), .Range("A100").End(xlUp))
rnData.AdvancedFilter Action:=xlFilterCopy, _
CopyToRange:=.Range("L1"), _
Unique:=True
'store the unique values in vaData
vaData = .Range(.Range("L2"), .Range("L100").End(xlUp)).Value
'clean up the contents of the temporary data storage
.Range(.Range("L1"), .Range("L100").End(xlUp)).ClearContents
End With
'display the unique values in vaData in the combo box already in existence on the worksheet.
With wsSheet.OLEObjects("ComboBox1").Object
.Clear
.List = vaData
.ListIndex = -1
End With
End Sub
Sub Populate_Combobox_Worksheet_Collection()
'The Excel workbook and worksheets that contain the data, as well as the range placed on that data
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnData As Range
Dim vaData As Variant 'the list, stored in a variant
Dim ncData As New VBA.Collection 'the list, stored in a collection
Dim lnCount As Long 'the count used in the On Error Resume Next loop.
Dim vaItem As Variant 'a variant representing the type of items in ncData
'Instantiate the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Sheet2")
'Using Sheet2,retrieve the range of the list in Column A.
With wsSheet
Set rnData = .Range(.Range("A2"), .Range("A100").End(xlUp))
End With
'Place the list values into vaData.
vaData = rnData.Value
'Place the list values from vaData into the VBA.Collection.
On Error Resume Next
For lnCount = 1 To UBound(vaData)
ncData.Add vaData(lnCount, 1), CStr(vaData(lnCount, 1))
Next lnCount
On Error GoTo 0
'Clear the combo box (in case you ran the macro before),
'and then add each unique variant item from ncData to the combo box.
With wsSheet.OLEObjects("ComboBox1").Object
.Clear
For Each vaItem In ncData
.AddItem ncData(vaItem)
Next vaItem
End With
End Sub
Sobre o colaborador
Dennis Wallentin é o autor do VSTO & .NET & Excel, um blog que se concentra em soluções .NET Framework para Excel e Serviços do Excel. Dennis vem desenvolvendo soluções Excel há mais de 20 anos e também é coautor de "Desenvolvimento do Excel Profissional: O Guia Definitivo para o Desenvolvimento de Aplicativos Usando o Microsoft Excel, VBA e .NET (2ª Edição)".
Suporte e comentários
Tem dúvidas ou quer enviar comentários sobre o VBA para Office ou sobre esta documentação? Confira Suporte e comentários sobre o VBA para Office a fim de obter orientação sobre as maneiras pelas quais você pode receber suporte e fornecer comentários.
Comentários
https://aka.ms/ContentUserFeedback.
Em breve: Ao longo de 2024, eliminaremos os problemas do GitHub como o mecanismo de comentários para conteúdo e o substituiremos por um novo sistema de comentários. Para obter mais informações, consulteEnviar e exibir comentários de