5

I'm quite new to VBA and I've been struggling with populating a combobox. I'm trying to fill a combobox with the contents of the first column in a spreadsheet so I can delete the associated row of data based on the combobox selection.

I've looked through several questions both here and elsewhere when making this question, but I haven't found anything that worked.

Below is the code I've tried. I'm somewhat lost as I've been trying to cobble together the different answers from other questions in order to get this to work, but to no avail. I expect the combobox to populate with the values from column 1, but it remains blank.

Attempt #1 This involved creating a dynamic range:

=OFFSET(PC_DataSheet!$A$2,0,0, COUNTA(PC_DataSheet!$A$1:$A$65536)-1,1)
Private Sub UserForm1_Initialize()

    Dim rngPCNumber As Range
    Dim ws As Worksheet

    Set ws = Worksheets("Sheet1")

    For Each rngPCNumber In ws.Range("PCNumber")
        Me.PC_ListComboBox.AddItem rngPCNumber.Value
    Next rngPCNumber

End Sub

Attempt #2

Private Sub UserForm1_Initialize()

    Dim arr() As Variant

    arr = Worksheets("Sheet1").Range("C2:" & lrow).Value
    PC_ListComboBox.List = arr

End Sub

Attempt #3

Private Sub UserForm1_Initialize()

    Dim vArr As Variant
    Dim i As Integer

    vArr = Sheet1.Range("A:1").Value

    With PC_ListComboBox.Clear
         For i = LBound(vArr) To UBound(vArr)
            .AddItem vArr(i)
         Next i
    End With

End Sub

Any help on this would be really appreciated!


EDIT: I've tried inserting the code suggested by Gary's Student into my UserForm_Initialize() Sub, but when I try to open the userform I get the following error message:

Run-time error '9': Subscript out of range

When I click debug, it highlights this code:

'Opens PC UserForm when pressed.
Private Sub AddPCButton_Click()

    UserForm.Show 'This line is the line highlighted by the debugger.

End Sub

I have no idea what's causing this...when I use the suggested code, I get an error message, but when I remove the code the userform functions flawlessly. Here's Private Sub UserForm_Initialize() with and without the suggested code.

'Clears and Initializes the form when first loaded.
Private Sub UserForm_Initialize()

    'Empties combo boxes.
    PC_OSTypeComboBox = ""
    PC_HDTypeComboBox = ""

    'Populates combo boxes.
    With PC_OSTypeComboBox
        .Clear
        .AddItem "Windows 8"
        .AddItem "Windows 7"
        .AddItem "Windows Vista"
        .AddItem "Windows XP"
        .AddItem "Windows 2000"
        .AddItem "Windows 98"
        .AddItem "Windows NT"
        .AddItem "Windows 95"
    End With
    With PC_HDTypeComboBox
        .Clear
        .AddItem "SATA"
        .AddItem "IDE"
        .AddItem "SCSI"
    End With

End Sub

This is including the suggested code:

'Clears and Initializes the form when first loaded.
Private Sub UserForm_Initialize()

    Dim N As Long, i As Long
    With Sheets("Sheet1")
        N = .Cells(Rows.Count, 1).End(xlUp).Row
    End With

    With PC_NumberComboBox
        .Clear
        For i = 1 To N
            .AddItem Sheets("Sheet1").Cells(i, 1).Value
        Next i
    End With

    'Empties combo boxes.
    PC_OSTypeComboBox = ""
    PC_HDTypeComboBox = ""

    'Populates combo boxes.
    With PC_OSTypeComboBox
        .Clear
        .AddItem "Windows 8"
        .AddItem "Windows 7"
        .AddItem "Windows Vista"
        .AddItem "Windows XP"
        .AddItem "Windows 2000"
        .AddItem "Windows 98"
        .AddItem "Windows NT"
        .AddItem "Windows 95"
    End With
    With PC_HDTypeComboBox
        .Clear
        .AddItem "SATA"
        .AddItem "IDE"
        .AddItem "SCSI"
    End With

End Sub
Community
  • 1
  • 1
ckemmann
  • 101
  • 1
  • 1
  • 8
  • @Mike Laren, just curious - I'm totally new to stack overflow, I'm just wondering why you made the edits you did? – ckemmann Apr 10 '15 at 16:35
  • You shouldn't write tags in titles since questions are already sorted and classified by tags. Also, things like "thank you" or "I got this error too" aren't really necessary. These are simple rules that help keep StackOverflow organized :) – Mike Laren Apr 10 '15 at 16:53
  • Ah ok, thank you! <--- not actually being facetious here ;-) – ckemmann Apr 10 '15 at 16:55
  • In your update, it looks like you might be referencing a nonexistent Worksheet - did you forget to update "Sheet1" from what @Gary's Student posted? – Lars Kemmann Apr 15 '15 at 13:42
  • Also note, I edited your question a bit as well. :) You can check the edit history to see the reasons people give for their edits. – Lars Kemmann Apr 15 '15 at 13:46
  • @LarsKemmann, I checked and I reference the same worksheet elsewhere in my code and it functions fine - it's this specific section that somehow keeps causing that error. I've found a another bit of code that does the same thing @Gary's Student does, but it also causes an error. `With Worksheets("Sheet1") PC_NumberComboBox.List = .Range("A1:A" & .Range("A" & .Rows.Count).End(xlUp).Row).Value End With` – ckemmann Apr 15 '15 at 13:47
  • What I mean is that the code you posted at first was using the sheet name "PC_DataSheet" and now your code says "Sheet1" -- which looks to me like a copy-paste error. Unless you've changed the worksheet name, in which case you should edit your question to make it consistent. – Lars Kemmann Apr 15 '15 at 13:49
  • That line you've just described is very elegant though. :) Definitely the way I'd write it. If the error is 'index out of range' then you need to figure out which array index is out of range. My first thought is the worksheet name is not in the list of worksheets. After that the code is really straightforward and robust. – Lars Kemmann Apr 15 '15 at 13:51
  • 1
    @LarsKemmann - The error is "subscript out of range" if that makes a difference. I've double-and-triple-checked for naming issues and found none. How can I verify that the worksheet name is included in the list of worksheets? – ckemmann Apr 15 '15 at 13:56
  • Try this: http://stackoverflow.com/questions/10654797/how-can-i-use-vba-to-list-all-worksheets-in-a-workbook-within-a-string – Lars Kemmann Apr 15 '15 at 14:00

3 Answers3

4

Here is a super simple example of creating and filling a Forms style combo-box:

Sub FormsStyleComboBox()
    ActiveSheet.DropDowns.Add(411, 14.25, 124.5, 188.25).Select
    N = Cells(Rows.Count, "A").End(xlUp).Row
    strng = Range("A1:A" & N).Address
    Selection.ListFillRange = strng
End Sub

For example:

enter image description here

EDIT#1

I created a UserForm called Demo containing a combo-box called MyBox

enter image description here

In a Standard Module I put:

Sub DisplayIt()
    Demo.Show
End Sub

and in the UserForm code area:

Private Sub UserForm_Initialize()
    Dim N As Long, i As Long
    With Sheets("Sheet1")
        N = .Cells(Rows.Count, 1).End(xlUp).Row
    End With

    With MyBox
        .Clear
        For i = 1 To N
            .AddItem Sheets("Sheet1").Cells(i, 1).Value
        Next i
    End With
End Sub

Running DisplayIt() produces:

enter image description here

This is based on this tutorial

Gary's Student
  • 95,722
  • 10
  • 59
  • 99
  • Thanks for the quick response, but I'm trying to populate a combo box in a userform, not one on the spreadsheet. How can I adapt your code to work for a combo box in a userform? – ckemmann Apr 10 '15 at 17:26
  • Please see my 'response edit'. I've tried implementing your code and it's causing an error when I try to open the userform. – ckemmann Apr 14 '15 at 16:28
  • @Mike Laren, Gary's Student...either of you have an idea - I'm totally stumped here. – ckemmann Apr 15 '15 at 11:45
  • @ckemmann , I think you have to reference the `comboBox` correctly... as [here](https://stackoverflow.com/questions/44083621/vba-how-to-reference-combobox-object) – Allstar May 05 '21 at 14:24
1
Private Sub UserForm_Initialize()

    Dim CS As Integer
    Dim CR As Integer
    Dim RF As Integer
    Dim PW As Integer
    Dim CD As Integer

        CS = ActiveWorkbook.Sheets("LISTS").Columns(2).End(xlDown).Row      
        CR = ActiveWorkbook.Sheets("LISTS").Columns(3).End(xlDown).Row      
        RF = ActiveWorkbook.Sheets("LISTS").Columns(4).End(xlDown).Row      
        PW = ActiveWorkbook.Sheets("LISTS").Columns(5).End(xlDown).Row      
        CD = ActiveWorkbook.Sheets("LISTS").Columns(6).End(xlDown).Row      

    With CB_CS
        .Clear
        For i = 2 To CS + 1
            .AddItem ActiveWorkbook.Sheets("LISTS").Cells(i, 2).Value
        Next i
    End With

    With CB_CR
        .Clear
        For i = 2 To CR + 1
            .AddItem ActiveWorkbook.Sheets("LISTS").Cells(i, 3).Value
        Next i
    End With

    With CB_RF
        .Clear
        For i = 2 To RF + 1
            .AddItem ActiveWorkbook.Sheets("LISTS").Cells(i, 4).Value
        Next i
    End With

    With CB_PW
        .Clear
        For i = 2 To PW + 1
            .AddItem ActiveWorkbook.Sheets("LISTS").Cells(i, 5).Value
        Next i
    End With

    With CB_CD
        .Clear
        For i = 2 To CD + 1
            .AddItem ActiveWorkbook.Sheets("LISTS").Cells(i, 6).Value
        Next i
    End With
End Sub

The code above is located in my UserForm Code (Right-Click on UserForm, then click 'view code')

I created a Worksheet call LISTS. Each column on that sheet is for a different combo-box. Once I filled it out and got the code working I hid the LISTS worksheet.

Each ComboBox I named CB_XX so note those names in the code

I start the code by defining the length of the lists (note this fails if you only have one item in the list but if you only have one item don't use a combo box)

Once I get the lengths I add the correct columns to the correct comboboxes. Note the +1 in each for/next loop. That is to add a blank at the end of each list to allow the user to empty the selection. Remove the +1 if you don't want that blank. I start at i = 2 to not show the header row on my LISTS sheet.

Kevin
  • 11
  • 1
0

So I tried the solution Gary's Student suggested, which worked when I created a new workbook with the code he provided, but for some reason the 'subscript out of range' error kept coming up when I implemented it in my project, no matter what I did to rename my worksheets in the workbook, including setting up a sub to list all the worksheets and call the sheet from there.

I opted instead to use an inputbox instead of a combobox, which ended up being a little more straightforward to code. Below is the code for anyone curious.

Private Sub DeletePCButton_Click()

'Assigns variables for delete sequence.
Dim PCNumberEntry As String
Dim Confirm As Integer
Dim r As Range
Dim c As Range
Dim cellsToDelete As Range
Dim m As Integer

'Asks for PC entry to be deleted.
PCNumberEntry = InputBox("Enter the number of the PC you wish to remove:", "Delete PC Entry", "PC 1", vbOKCancel)

'Closes inputbox when cancel is pressed.
If PCNumberEntry = "" Then
    Exit Sub
End If

'Searches worksheet column "A" and finds any existing PC entries.
Set r = Sheet1.Range("A:A")
For Each c In r

    'Checks for matching entry in worksheet to begin delete sequence.
    If (c.Value) = PCNumberEntry Then
        m = True

        'Asks for confirmation from user before deleting entry.
        Confirm = MsgBox("Warning! Once deleted, an entry cannot be restored! Only proceed if you are sure you wish to delete a row.", vbYesNo Or vbExclamation)

        'Cancels delete operation when "No" button is pressed.
        If Confirm = vbNo Then
            Exit Sub
        End If

        'Deletes entry and informs user of successful operation.
        If cellsToDelete Is Nothing Then
            Set cellsToDelete = c
            Call cellsToDelete.EntireRow.delete
            MsgBox ("The entry was deleted.")
        End If

    End If

Next c

    'Displays error message if no matching entry is found.
    If m = False Then
        MsgBox ("No entry with that number was found!")
    End If

On Error Resume Next

End Sub

ckemmann
  • 101
  • 1
  • 1
  • 8