PDA

View Full Version : Populate List box using For Loop...



wpeacock
2005-01-11, 06:57 AM
I'm trying to populate a list box with a list of numbers starting with the value 4 and increasing by 0.5 each time, ie
4.0
4.5
5.0
5.5

the following code will only produce "4" in the list box.
How can I get the rest of the numbers to appear? and can the list box number be formatted to "4.0"

Private Sub UserForm_Initialize()
Dim i As Double

For i = 4 To 30 Step (0.5)
ListBox1.AddItem (i)
Exit For
Next i

End Sub

warren.medernach
2005-01-11, 02:41 PM
Hello wpeacock.

Couple things I can see...

You're calling 'Exit For' inside of the loop without any checking so it's firing every time... So the first time it runs, it adds '4' to the listbox, and then calls Exit For, and it's done...

Another thing
I think you need to manually calculate and increment 'i', as the Step value must be a positive or negative integer...

Hope this helps

Warren M

RobertB
2005-01-11, 02:46 PM
You have two mistakes (actually 3):

You have the stepping increment wrapped in parens. Looking in the help files (F1 on the For keyword) could have told you about that mistake.

You have an Exit For as the second statement inside the For loop. What is going to happen if you have that there?

The 3rd "mistake" is that you evidently don't know how to use the debugging tools of the VBIDE. Learn how to set breakpoints, use the immediate window, and so on to help you debug your code. If you don't learn how to use the debugging tools on your own, and rely on posting questions, it will take you much longer to write your code.

Not that I'm trying to discourage your from posting questions, please do! That is one good way to learn how to refine your code.

Public Sub Test()
Dim i As Double
For i = 4# To 30# Step 0.5
Debug.Print i
Next i
End Sub

warren.medernach
2005-01-12, 02:39 PM
Cool! stepping by 0.5...
Awesome!
Always learining something everyday...

Thanks Robert...