List boxes

J

Joanne

I have the following code which is meant to take multiple selections from a
list box and paste them into a document at the site of a bookmark. I'm not
getting the value from the list box correctly. Any help would be greatly
appreciated.

Public Sub AddPracticeAreas()
Dim i As Integer
Dim strPractice(10) As String
ActiveDocument.Bookmarks("bmPracticeAreas").Select
For i = 0 To 9
If frmAttyBio.listPracticeAreas.Selected(i) = True Then
Selection.Collapse wdCollapseEnd
strPractice = frmAttyBio.listPracticeAreas.Selected(i)
Selection.Text = "| " & strPractice
If Selection.Text = strPractice(0) Then
Selection.Text = strPractice
End If
End If
Next i
End Sub
 
C

Chuck Henrich

How's this? It uses a range object rather than the selection object, and
builds the string during the for-next loop rather than messing with the
selection object during the loop. It doesn't use an array because it's not
necessary (unless there's something I'm misunderstanding).

In any case, the reason you weren't getting the selected text from the list
box is that you need to use .List(i) instead of .Selected(i) to get the
selected text.

Public Sub AddPracticeAreas()

Dim i As Integer
Dim strPractice As String
Dim rngRange As Range

Set rngRange = ActiveDocument.Bookmarks("bmPracticeAreas").Range

For i = 0 To 9
If frmAttyBio.listPracticeAreas.Selected(i) = True Then
strPractice = _
strPractice & " | " & frmAttyBio.listPracticeAreas.List(i)
End If
Next i

If Len(strPractice) > 0 Then
strPractice = strPractice & " |"
End If

rngRange.Text = strPractice

End Sub

HTH
 
C

Chuck Henrich

PS should have included the following just before "End Sub":

set rngRange = Nothing
 
J

Joanne

Thank you very much for your help. But can you tell me how I get the value
of the list box into strpractice? It seems to be empty.
 
C

Chuck Henrich

The strPractice string is built by concatenating all the selected items in
the list box, just as you were attempting to do in your posted code. I
tested the code I posted on a list box in a form using your object names and
it works fine. How are you running the macro? Is anything selected in the
list box when you run the macro?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top