How to Populate a Combobox

前端 未结 3 547
忘掉有多难
忘掉有多难 2021-01-13 01:26

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 de

3条回答
  •  长发绾君心
    2021-01-13 02:25

    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

提交回复
热议问题