You are here:

Excel/need VBA solution for listbox control



This should be simple but for the life of me I can't figure out what I've done wrong.

I have written some basic code that allows the user to select a range of cells, click an "add" button which then transfers the cell contents into a userform listbox.  I then have a button on the userform that hides the form to allow the user to make additional selections, click the Add button, and have the values added to the listbox (appended to the end of the data that was originally selected).  It supposed to function almost like an "Add to Cart" / "Continue shopping" type form.

Here's the problem; I can get it to add the data to the listbox and to return to the sheet.  But the second time through, the selections just replace the original list instead of adding to it.  Im looking at my code and seeing that I'm overwriting my variable but Im a VBA newbie and am not sure how to fix it.  I've tried to create a new variable that combines the two ranges but haven't been able to get it to work.

Here is what I have so far:

Private Sub UserForm_Activate()
Dim rng As Range
Dim nrng As Range
If Listboxitems.ListCount = 0 Then
Set rng = Selection
Listboxitems.List = rng.Cells.Value
Set nrng = Selection
Listboxitems.List = nrng.Cells.Value
End If
End Sub

I keep searching online but all I can find is all the ways to populate a list box, but not how to add items to an already existing listbox list.  



I would use additem.  I assume your selection will be a single column

Private Sub UserForm_Activate()
Dim rng As Range

Set rng = Selection
for each cell in rng
 Listboxitems.additem cell.Value

End Sub

Tom Ogilvy

About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here


All Answers

Answers by Expert:

Ask Experts


Tom Ogilvy


Selected as an Excel MVP by Microsoft since 1999. Answering Excel questions in Allexperts since its inception in 2001. Able to answer questions on almost all aspects of Excel's internal capabilities. If seeking a VBA solution, please specify that in your question itself so I give you the answer you want. [Excel has weak protection - if you are distributing an application, I don't answer questions on how to protect your project from your users.]


Extensive experience.

Master of Science (MS) degree Operations Research (ORSA)

Awards and Honors
Microsoft MVP in Excel.

©2017 All rights reserved.