2016-11-22 65 views
0

我试图从两个列表中删除组合框中的空白记录。从两个列表中删除组合框中的空白

这是我的代码:

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 

我不知道我做错了。

+0

如果你更改为:如果ws.Cells(I,J).value的<> vbNullString和ws.Cells(I,J ).Value <>“”然后 –

+0

如果同一行上的两个单元格都是空白或其中任何一个,您想要删除它们吗?你现在正在做的是“任何”,但你可能会失去同一行上的正确关联。 –

+0

仍然有空白,即时通讯使用只有一行填充测试,该行的数据显示,但我得到了很多空白,我没有这个问题与一列组合框 –

回答

1

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

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 
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 
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),会给我一个错误

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