VBA comboBox多列删除空白行和列出的特定值

问题描述 投票:0回答:1

我有一个comboBox,其中列出了两列(A和H)。列出项目的条件是:1.从A列中添加不包含空白行的项目2.在H

列中添加不等于零的项目

我能够使用此代码执行第一个条件:

Private Sub UserForm_Activate()

Dim currentCell As Range

With ComboBox1

.ColumnCount = 2
.ColumnWidths = "70;30"
.ColumnHeads = False
.BoundColumn = 1

With Worksheets("Sheet")
    With .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        For Each currentCell In .Cells
            If Len(currentCell) > 0 Then
                With Me.ComboBox1
                    .AddItem currentCell.Value
                    .List(.ListCount - 1, 1) = currentCell.Offset(, 7).Value
                End With
            End If
        Next currentCell
    End With
End With
End With


End Sub

我试图在第二种情况下更改该部分,但这不起作用:

With Worksheets("Sheet")
    With .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        For Each currentCell In .Cells
            If Len(currentCell) > 0 & currentCell.Offset(, 7).Value <> 0 Then
                With Me.ComboBox1
                    .AddItem currentCell.Value
                    .List(.ListCount - 1, 1) = currentCell.Offset(, 7).Value

谢谢

excel vba list combobox multiple-columns
1个回答
0
投票
Private Sub UserForm_Initialize()
Dim Sh As Worksheet, rng As Range, arr(), cL As Range
Set Sh = ThisWorkbook.Worksheets("Sheet1")

'Make union of cells in Column A based on the two conditions given
For i = 1 To Range("A" & Rows.Count).End(xlUp).Row
    If Sh.Range("A" & i).Value <> "" And Sh.Range("H" & i).Value <> 0 Then
        If rng Is Nothing Then
        Set rng = Sh.Range("A" & i)
        Else
        Set rng = Union(rng, Sh.Range("A" & i))
        End If
    End If
Next

'Make array of values of rng ang corresponding H Column cells
ReDim arr(rng.Cells.Count - 1, 1)
i = 0
For Each cL In rng
    arr(i, 0) = cL.Value
    arr(i, 1) = cL.Offset(0, 7).Value
    Debug.Print rng.Cells(i + 1).Address; arr(i, 0); arr(i, 1)
i = i + 1
Next

'Assign the array to the ComboBox
ComboBox1.ColumnCount = 2
ComboBox1.List = arr

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.