gpt4 book ai didi

Excel VBA 将项目添加到组合框而不重复项目

转载 作者:行者123 更新时间:2023-12-03 00:10:47 25 4
gpt4 key购买 nike

我想将以下项目添加到组合框中,但如果某个项目有重复项,则只应添加一个。

   A
1 john
2 john
3 marry
4 marry
5 john
6 lisa
7 frank
8 marry

我希望组合框结果为 johnmarrylisafrank(四个唯一的项目)共八项)。

<小时/>

我的代码是:

Private Sub Workbook_Open()

Application.EnableEvents = False

With Sheet2.ComboBox1

For Each Cell In Sheet1.Range("A1:A6348")
If Not ComboBox1.exists(Cell.Value) Then
.AddItem Cell.Value
End If
Next

End With

End Sub

最佳答案

添加唯一项的另一种方法是使用 Dictionary 对象。

见下文:

Dim rngItems As Range
Dim oDictionary As Object

Set rngItems = Range("A1:A8")
Set oDictionary = CreateObject("Scripting.Dictionary")

With Sheet1.ComboBox21
For Each cel In rngItems
If oDictionary.exists(cel.Value) Then
'Do Nothing
Else
oDictionary.Add cel.Value, 0
.AddItem cel.Value
End If
Next cel
End With

关于Excel VBA 将项目添加到组合框而不重复项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28609687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com