Excel vba: Getting range from a column with empty

2019-09-07 16:00发布


I have a column that I want to extract info from (with empty cells) based on a value from another column.
This question helped me quite a lot with but I now have a column with multiple empty cells and the formula is not working...

enter image description here

Code:

Private Sub techCombo_Change()

Dim ws As Worksheet
Dim rFound As Range

Dim cCmbBox As MSForms.ComboBox
Set cCmbBox = ActiveWorkbook.Sheets(1).custCombo
cCmbBox.Clear

With Me.cmbSheet
    If .ListIndex = -1 Then Exit Sub
    Set ws = ActiveWorkbook.Sheets(.Text)
End With

With Me.techCombo
    If .ListIndex = -1 Then Exit Sub
    Set rFound = ws.Columns("A").Find(.Text, ws.Cells(ws.Rows.Count, "A"), xlValues, xlWhole)
End With

If Not rFound Is Nothing Then
    If Trim(Len(rFound.Offset(2, 1).Text)) = 0 Then
        cCmbBox.AddItem rFound.Offset(1, 1).Value
    Else
        cCmbBox.List = ws.Range(rFound.Offset(1, 1), rFound.Offset(1, 1).End(xlDown)).Value
    End If
End If

End Sub

An image showing an example:
So selecting VoLTE should populare a combobox with K1, K3, I7, U6 enter image description here

1条回答
做个烂人
2楼-- · 2019-09-07 16:37

Try to replace this:

If Not rFound Is Nothing Then
    If Trim(Len(rFound.Offset(2, 1).Text)) = 0 Then
        cCmbBox.AddItem rFound.Offset(1, 1).Value
    Else
        cCmbBox.List = ws.Range(rFound.Offset(1, 1), rFound.Offset(1, 1).End(xlDown)).Value
    End If
End If

with this:

If Not rfound Is Nothing Then
 LastRow = Ws.Cells(Ws.Rows.Count, rfound.Column + 1).End(xlUp).Row
 j = rfound.Row
 i = 1

 Do While j <= LastRow And rfound.Offset(i) = ""
  If rfound.Offset(i, 1) <> "" Then
   cCmbBox.AddItem rfound.Offset(i, 1)
  End If
  i = i + 1
  j = j + 1
 Loop
End If
查看更多
登录 后发表回答