Hi I am trying to fill a combobox with the files from a FileListBox the code i am using is

Private Sub Form_Load()

File1.Path "C:\Images"
File1.Refresh
 
 If File1.ListCount > 0 Then
   
    For i = File1.ListCount To -1
      Combo1.AddItem File1.List(i)
    Next
End If

End Sub

The FileListBox fills with the file from the folder that i want but the Combo Box doesn't come somebody give me some help with this please I think that the problem is with this line For i = File1.ListCount To -1

Alan

Try changing your for loop from a reverse count to a normal count:

Private Sub Form_Load()
File1.Path = "C:\Images"
File1.Refresh
 
 If File1.ListCount > 0 Then
   
    For i = 0 To File1.ListCount - 1
      Combo1.AddItem File1.List(i)
    Next
End If
End Sub

HI Comatose

Thanks that worked I am new to VB but am learning everyday can you explain to me why reversing it worked or even why it didnt work in the first place

Thanks

Technically, you could have "gone the other way", but when doing a for loop, it's default behavior is to count up. So, behind the scenes there is a test condition being applied to the for loop.... for example: for I = 0 to 9 is going to say "ok, is I less than 9" if the answer is yes, then do the stuff between for and next. Then, it's going to Add 1 to I, and say "ok, I is 1 [then 2 and 3, etc, etc], is it less than 9?" It will continue this process until I becomes 9. When you say: for I = 10 to 1 , the programming language isn't going to change it's behavior, just because you decided to change the numbers.... so, dutifully, it says: "ok, I is 10 right off the bat, is I (10) less than 1 (or -1 or whatever)". Naturally, 10 is not less than 1 or negative 1.... or even 9, so the for loop never actually even runs once. It just compares, sees that 10 is not less than -1, and says screw it, and moves on.

You can change the behavior of the for loop, however, to decrement instead of increment (to count down instead of up) but be advised, that this is not the standard way of doing things. Meaning, if you ever share your code with someone, or you end up working in a team setting, someone might have a more difficult time understanding your code, because you aren't doing things normally. However, you could modify your statement to run backward with something like this:

For i = File1.ListCount - 1 To 0 Step -1
     Combo1.AddItem File1.List(i)
Next

The key here, is the "step" keyword. The step keyword tells the for loop what kind of behavior it should apply when dealing with the counter variable. You could do a for loop with a step 2, which would actually only execute code on every other iteration....

HI

thank you for the explanation i can see where you a going with this and i shall try to remember that when coding the next For loop .

Alan

This question has already been answered. Start a new discussion instead.