Programmatically scroll a List Box

  • Thread starter Thread starter Silvio
  • Start date Start date
S

Silvio

I would like to add two buttons (“Next†and “Go Backâ€) in my form to navigate
my List Box items from the top to the bottom. The buttons should perform the
same action as the Up and Down arrow to navigate the list vertically. Can it
be done? If so, how?

Thank you
 
Silvio said:
I would like to add two buttons ("Next" and "Go Back") in my form to
navigate
my List Box items from the top to the bottom. The buttons should perform
the
same action as the Up and Down arrow to navigate the list vertically. Can
it
be done? If so, how?

Thank you

This is air code but I'm pretty sure it'll do the job:

Private Sub btnNext_Click()
If lstItems.Index < lstItems.ListCount - 1 Then
lstItems.Index = lstItems.Index + 1
Else
lstItems.Index = 0
End If
End Sub

Private Sub btnGoBack_Click()
If lstItems.Index > 0 Then
lstItems.Index = lstItems.Index - 1
Else
lstItems.Index = lstItems.ListCount - 1
End If
End Sub
 
It does not work. "Index is not valid". I have tried .ListIndex and also does
not work. Any idea?
 
OK I got it to work. I needed to set focusn on the list first and use
..ListIndex. For everyone's benefit here is the full working codes:

Private Sub GoBack_Click()
Me.MyFiles.SetFocus
If Me.MyFiles.ListIndex > 0 Then
Me.MyFiles.ListIndex = Me.MyFiles.ListIndex - 1
Else
Me.MyFiles.ListIndex = Me.MyFiles.ListCount - 1
End If
End Sub

Private Sub GoNext_Click()
Me.MyFiles.SetFocus
If Me.MyFiles.ListIndex < Me.MyFiles.ListCount - 1 Then
Me.MyFiles.ListIndex = Me.MyFiles.ListIndex + 1
Else
Me.MyFiles.ListIndex = 0
End If
End Sub


Thank you Stuart for your help!
 
Silvio said:
OK I got it to work. I needed to set focusn on the list first and use
.ListIndex. For everyone's benefit here is the full working codes:

Private Sub GoBack_Click()
Me.MyFiles.SetFocus
If Me.MyFiles.ListIndex > 0 Then
Me.MyFiles.ListIndex = Me.MyFiles.ListIndex - 1
Else
Me.MyFiles.ListIndex = Me.MyFiles.ListCount - 1
End If
End Sub

Private Sub GoNext_Click()
Me.MyFiles.SetFocus
If Me.MyFiles.ListIndex < Me.MyFiles.ListCount - 1 Then
Me.MyFiles.ListIndex = Me.MyFiles.ListIndex + 1
Else
Me.MyFiles.ListIndex = 0
End If
End Sub


Thank you Stuart for your help!

I forgot the need to give the listbox focus, sorry.

Ok now we've established that it does indeed work, let's tidy it up a bit:

Private Sub GoBack_Click()
With Me.MyFiles
.SetFocus
.ListIndex = Iif(.ListIndex > 0, .ListIndex - 1, .ListCount - 1)
End With
End Sub

Private Sub GoNext_Click()
With Me.MyFiles
.SetFocus
.ListIndex = Iif(.ListIndex < .ListCount - 1, .ListIndex + 1, 0)
End With
End Sub

A lot easier to read, I think you'll agree.
 
Back
Top