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

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

我无法删除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

提前感谢

excel vba combobox row blank-line
2个回答
1
投票

尝试以下代码...

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

希望这会有所帮助!


0
投票

使用数组的另一种方法

Private Sub CommandButton1_Click()
    Dim rngCombo As Range
    Dim lRow As Long, i As Long, 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 COl 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
© www.soinside.com 2019 - 2024. All rights reserved.