这是我在这个网站或其他地方都没有找到的情况:
我的 VBA 用户表单上有一个组合框“数字”。我想用“名称”表第 1 列中的数据以及“家庭”表第 1 列中的数据来填充它。两个表都在同一张表“Sheet2”上。
我还希望我的组合框不显示重复值(在工作表表格列中我想保留重复值)。
我想将代码放在 Userform Initialize 事件下。
P.S:再次强调;这不是一个多列组合框,而只是一个包含来自两个表的数据的普通组合框。
***更新:我尝试了两种解决方案:
1-联合范围,
2- 分别循环遍历每个范围和 AddItem 命令。没有一个有效,我仍然只看到我的组合中的第一个范围。
我不喜欢在VBA中引用表格,所以我写了一个应该基于范围的命题。
如果您想要引用 ListObjects 的代码,请在此处查看:VBA:如何使用表标题引用列,以便我可以在单元格引用中使用该列
Private Sub UserForm_Activate()
Dim rng As Range
Dim lastRow As Integer
Numbers.Clear
lastRow = Worksheets("mdList").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious, After:=Range("A1")).Row 'in after pot Names table 1st cell
For Each rng In Worksheets("Sheet2").Range("A1:A" & lastRow) 'Names table range
Numbers.AddItem md.Value
Next md
lastRow = Worksheets("mdList").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious, After:=Range("A1")).Row 'in after pot Families table 1st cell
For Each rng In Worksheets("Sheet1").Range("A1:A" & lastRow) 'Families table range
Numbers.AddItem md.Value
Next md
End Sub
打开表单时代码将激活。
Private Sub UserForm_initialize()
Dim wsNames(): wsNames = VBA.Array("Sheet2", "Sheet2")
Dim tblNames(): tblNames = VBA.Array("Names", "Families")
Dim tblColumns(): tblColumns = VBA.Array(1, 1)
Dim wb As Workbook: Set wb = ThisWorkbook
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim ws As Worksheet, lo As ListObject, rg As Range, Data, rVal
Dim n As Long, r As Long, rCount As Long
For n = 0 To UBound(wsNames)
Set ws = wb.Sheets(wsNames(n))
Set lo = ws.ListObjects(tblNames(n))
Set rg = lo.ListColumns(tblColumns(n)).DataBodyRange
rCount = rg.Rows.Count
If rCount = 1 Then
ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
Else
Data = rg.Value
End If
For r = 1 To rCount
rVal = Data(r, 1)
If Not IsError(rVal) Then ' not an error
If Len(CStr(rVal)) > 0 Then ' not blank
If Not dict.Exists(rVal) Then
dict(rVal) = Empty
End If
End If
End If
Next r
Next n
If dict.Count = 0 Then ' only errors and blanks
Numbers.Clear
Else
Numbers.List = dict.Keys
End If
End Sub
如果可以的话,我想回答我自己的问题,因为没有任何地方可以正确且简单地解决这样的问题:
从同一张纸上的两个不同表格填充组合框。组合框不应显示重复项。
代码其实很简单:
Private Sub UserForm_initialize()
Dim cloc As Range
Dim j As Integer
Dim x As Integer
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("sheet2")
Dim rng As Range
Set rng = sh.ListObjects("Names").ListColumns(1).DataBodyRange
Dim rng2 As Range
Set rng2 =sh.ListObjects("Families").ListColumns(1).DataBodyRange
Numbers.List = Sheets("sheet2").ListObjects("Names").ListColumns(1).DataBodyRange.value
'''''''''''to add the other range (first column of the second table)'''''''''''
For Each cloc In rng2
Numbers.AddItem cloc.value
Next cloc
''''''''''''''''''''''''''''''''''''''''''''avoid duplicates'''''''''''''''
For x = 0 To Numbers.ListCount - 2
For j = Me.Numbers.ListCount - 1 To x + 1 Step -1
If Numbers.List(x) = Numbers.List(j) Then 'repeated
Numbers.RemoveItem (j)
End If
Next j
Next x
End Sub