Search code examples
vbaexcellistboxuserform

Possible to use logic statement directly in UserForm.AddItem?


I know and understand the usual method of adding items to a ListBox using a logical test:

If a = 1 Then
    ListBox1.AddItem x
End If

However, I was wondering if it is at all possible to .AddItem directly with a logic statement? Something like:

ListBox1.AddItem If a = 1

This is not a burning question that has me stumped. I just want to know if there is an alternative method to add to my knowledge base.


Solution

  • As far as I am aware you cannot add logic statment directly with .addItem method. However, you can define a function, for example:

    Function check(b As Integer)
    
        If b = 1 Then
    
            check = "x"
    
        Else
    
        End If
    
    End Function
    

    And then use .addItem like:

    ListBox1.AddItem check(a)
    

    Edit: As @robinCTS noticed unfortunatelly this method will result on adding blank item do listbox item. So it would only work if you would like to have an alternative (for example add "x" or "y" depending on condition). It appears that issue with blank row could be only solved by removing it after .addItem line.