用两个列表从组合框中删除空格

时间:2016-11-22 20:57:48

标签: vba excel-vba excel

我正在尝试使用两个列表从组合框中删除空白记录。

这是我的代码:

Private Sub UserForm_Initialize()
Dim N As Range
Dim LastRow As Integer
Dim ws As Worksheet

PREST.ColumnCount = 2
Set ws = Worksheets("L_Location")
LastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
Dim i, j As Integer

Dim location(2 To 100, 1 To 2) As String


For j = 1 To 2
For i = 2 To LastRow
If ws.Cells(i, j).Value <> vbNullString Then
location(i, j) = ws.Cells(i, j).Value
End If
Next i
Next j
PREST.List = location
End Sub

我不知道我做错了什么。

4 个答案:

答案 0 :(得分:1)

你有空白,因为你的2D数组已经有100行的大小。一个简单的解决方法是首先计算非空行,然后相应地对Array进行维度。

Dim location() As String
Dim count As Long
count = Range("A2:A" & LastRow).SpecialCells(xlCellTypeConstants).Cells.count

ReDim location(1 To count, 1 To 2)

'then continue from here to fill the array

答案 1 :(得分:0)

此代码将使用您的范围值填充组合框,然后删除任何空项:

Private Sub UserForm_Initialize()

    Dim LastRow As Long
    Dim ws As Worksheet

    PREST.ColumnCount = 2
    Set ws = Worksheets("L_Location")
    LastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
    Dim i As Long ', j As Integer


    PREST.List = ws.Range("a1:b" & LastRow).Value
    For i = PREST.ListCount - 1 To 0 Step -1
     If PREST.List(i) = "" Then PREST.RemoveItem i
    Next

End Sub

答案 2 :(得分:0)

我试过了:

Dim location() As String
ReDim location(LastRow - 2, 1)

For j = 0 To 1
For i = 0 To LastRow - 2
  If ws.Cells(i + 2, j + 1).Value <> vbNullString And ws.Cells(i + 2, j +  1).Value <> "" Then
    location(i, j) = ws.Cells(i + 2, j + 1).Value
  End If
Next i
Next j
PREST.List = location

这似乎有效,但我猜如果列表为空(如果列表为空,它会给我一个错误)(lastrow = 1)

答案 3 :(得分:0)

由于您说同一行中的任何两个单元格都是空白或带有值,因此您可以如下所示:

Dim cell As Range
Dim i As Long, j As Long

PREST.ColumnCount = 2
With Worksheets("L_Location") '<--| reference your worksheet
    With .Range("A2", .Cells(.Rows.Count,1).End(xlUp)).SpecialCells(xlCellTypeConstants) '<--| reference its column A not empty cells from row 1 down to last not empty one
        Dim location(1 To .Count, 1 To 2) As String '<--| size your array rows number to that of referenced cells
        For Each cell In .Cells '<--| loop through referenced cells
            i = i + 1 '<--| update array row index
            For j = 1 To 2 '<--| loop through array columns
                location(i, j) = cell.Offset(j -1).Value '<--| fill array
            Next j
        Next cell
    End With
End With


PREST.List = location