• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Last item of combo box as default value in userform

Hi,

Need your help on this please:

What vba syntax can I use to to set the last item of combo box as default value in userform?

Your help will be greatly appreciated.

Thanks,
 
Hi Lui,

I have manually added 10 items to the combo box using a for loop..
Code:
    Dim i As Byte
    For i = 1 To 10
        ComboBox1.AddItem "Item " & i
    Next

And In order to set the last item as combo box as default value, I have written the following code:
Code:
    ComboBox1.Text = ComboBox1.List(ComboBox1.ListCount - 1)

In the above line, comboxbox1 is the name of the combo box and Listcount gives the total items in the combo box

The above piece of code is to be written in the UserForm_Initialize sub procedure under the code window of the form object
Code:
Private Sub UserForm_Initialize()
    Dim i As Byte
    For i = 1 To 10
        ComboBox1.AddItem "Item " & i
    Next
    ComboBox1.Text = ComboBox1.List(ComboBox1.ListCount - 1)
End Sub

Hope this helps!!
 
Hi Ramesh,

Thanks for the immediate reply....the code works but the loop part doesn't apply to me - items in the ComboBox are coming from one of my worksheets (logs). Said ComboBox is being populated and therefore increasing in data. How can I substitute this using the "For i = 1 To 10" function?

I will be using this in Userform7 of the attached file.
 

Attachments

  • Form_Templates1.xlsm
    173.3 KB · Views: 15
Thanks for sharing this file...

First thing I have observed on the drop down is, I see there are lot of blank values, along with the actual text, in order to not to add these blank values in the drop down, I have modified your for loop to add non blank values..

Code:
For Each rngColor In ws.Range("CPARNos")
    If rngColor.Value <> "" Then
        Me.ComboBox12.AddItem rngColor.Value
    End If
Next rngColor

Now, after the for loop, I have added the following line of code to have the last item in the combo box to be the default text

Code:
ComboBox12.Text = ComboBox12.List(ComboBox12.ListCount - 1)

Hope that helps!!
 
Back
Top