删除 VBA 中多列 ComboBox 中的空白行

Remove blank rows in a multicolumns ComboBox in VBA

我无法删除 ComboBox 中显示的空白行并保留我的两列。 我试过这段代码:

  For Each c In Range(Range("A3"), Range("A" & Rows.Count).End(xlUp)) 
       If c.Value <> vbNullString Then ComboBox1.AddItem c.Value
  Next c

但这就是行不通,有没有办法更改两列的范围? 所以我的代码带有 ComboBox 的参数。

Private Sub UserForm_Activate()

Dim c As Range

   With ComboBox1

     .ColumnCount = 2

     .ColumnWidths = "70;30"

     .ColumnHeads = False

     .BoundColumn = 1

     .List = Union(Range("A2:A100"), Range("B2:B100")).Value


  For Each c In Range(Range("A3"), Range("A" & Rows.Count).End(xlUp)) 
       If c.Value <> vbNullString Then ComboBox1.AddItem c.Value
  Next c

End With


End Sub

提前致谢

试试下面的代码...

Dim currentCell As Range

With Worksheets("Sheet1") 'change the sheet name accordingly
    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(, 1).Value
                End With
            End If
        Next currentCell
    End With
End With

希望对您有所帮助!

另一种使用数组的方法。这将在非常大的范围内更快。

Option Explicit

Private Sub CommandButton1_Click()
    Dim rngCombo As Range
    Dim lRow As Long, i As Long, n As Long
    Dim blanks As Long
    Dim ws As Worksheet
    Dim preArray As Variant, NewArray() As String

    '~~> Set this to the relevant sheet
    Set ws = Sheet1

    With ws
        '~~> Find last row of Col A
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Define your range
        Set rngCombo = .Range("A3:B" & lRow)

        '~~> Store that range in an array
        preArray = rngCombo.Value

        '~~> Get blanks in Column 1 of that range
        blanks = Application.WorksheetFunction.CountBlank(rngCombo.Columns(1))

        '~~> Define your new array to store data
        ReDim NewArray(rngCombo.Rows.Count - blanks - 1, 1 To 2)

        '~~> Populate the new array
        For i = LBound(preArray) To UBound(preArray)
            If Len(Trim(preArray(i, 1))) <> 0 Then
                NewArray(n, 1) = preArray(i, 1)
                NewArray(n, 2) = preArray(i, 2)
                n = n + 1
            End If
        Next i
    End With

    With ComboBox1
        .ColumnCount = 2
        .ColumnWidths = "70;30"
        .ColumnHeads = False
        .List = NewArray '<~~ Assign array to list
    End With
End Sub