printing a list in a message box

L

Larry

I can display the members of a collection in one message box after
another, like this:

For i = 1 To Documents.Count
MsgBox Documents(i)
Next i

I have to keep pressing OK until all the message boxes have been
displayed.

But, how can I display a single message box that lists the entire
collection in that one message box?

Thanks,
Larry
 
J

Jonathan West

Hi Larry

try this

Dim strDocs as String
For i = 1 To Documents.Count
strDocs = strDocs & vbCrLf & Documents(i)
Next i
If Len(strDocs) > 0 Then
strDocs = Mid$(strDocs, 3)
MsgBox strDocs
Else
MsgBox "No documents open"
End If
 
L

Larry

Thanks very much, Jonathan. This is simple but powerful code, and not
something I ever would have thought of, since it's counterlogical (at
first) to think that something equals itself plus something else. (I've
used other macros where a variable keeps getting something added to
itself with each loop, but never something quite like this.) It was
confusing at first regarding the first document, since how can strDocs
equal StrDocs when we don't even know yet what StrDocs is? Then I
realized that strDocs in the first loop simply registers as nothing, and
only later acquires content.

Here's a simplified version of the code to make this more clear to
myself (and anyone else reading this):

Dim strDocs As String
For i = 1 To Documents.Count
strDocs = strDocs & vbCrLf & Documents(i)
Next i
MsgBox strDocs

On the first loop, strDocs equals the empty space of strDocs (which has
no content yet) plus a return plus the first document. On the second
loop, strDocs equals what it already equalled, i.e., that empty space
plus the first document, PLUS an additional paragraph return and the
second document. On the third loop, strDocs equals everything it
previously equalled PLUS another paragraph return and the third
document. And after the documents are all run through, the message box
displays this one continual string consisting of all the documents
interspersed with paragraph return. This is great.

Question: why do you use vbCRLf instead of just vbCr (since the latter
seems to work as well)?

Also, I see the purpose of the Mid$(strDocs,3) is to eliminate the first
two characters of StrDocs, which are the empty space of the initial
strDocs and the paragraph return, so that the contents appearing in the
message box are not preceded by unnecessary empty lines:

If Len(strDocs) > 0 Then
strDocs = Mid$(strDocs, 3)
MsgBox strDocs
Else
MsgBox "No documents open"
End If

Larry
 

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