简体   繁体   中英

Excel VBA: How to populate a combobox with cell values from each row if conditions are met

I'm trying to populate a combobox with the values in column B of each row, but only if the following conditions are met:

  1. The cell in column B is not empty/has a value.
  2. The cell in column H is empty/has no value.

The code needs to only consider values after row 3 (because those are table headings) and it needs to be able to adjust to changes in the worksheet.

If anyone has some tips I'd really appreciate it. I've been struggling with this for days.

I can post my code if it would help, but it's a mess from all the different things I've tried.

You can try the following code. I have put it in the Initialize event handler. You may have to change that. Please rename ComboBox1 to the name of your combo box.

Private Sub UserForm_Initialize()

  Dim lngLastRow As Long                              'index of bottom row of ActiveSheet
  Dim rngSource As Range                              'range containing list item candidates
  Dim i As Long                                       'counter used in For...Next
  
  lngLastRow = [A1].SpecialCells(xlLastCell).Row      'get index of bottom row
  Set rngSource = [B4].Resize(lngLastRow - 3, 1)      'first cell to bottom row, 1 cell wide
  With rngSource.Cells
    For i = 1 To lngLastRow - 3                       'loop through all cells of rngSource
      If Not IsEmpty(.Item(i)) And IsEmpty(.Item(i).Offset(0, 6)) Then 'test col. B and H
        ComboBox1.AddItem (.Item(i).Value)            'add col. B value to ComboBox
      End If
    Next i
  End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM