Search code examples
vbaloopsmsgbox

Loop result post Msgbox new line


I have a loop looking for text in a column (that is working) and I want to post the result in a MsgBox, but when I use the msgbox in or outside the loop I will get a msgbox for every result found or only one msgbox with one result. What I would like is to make it post every result in 1 msgbox with a line break after each result.

I know the first code is not the prettiest or best way to go around finding duplicates and I should use an array for it, but it's the only way I got it to work.

The first code finding duplicates (not relevant for the question):

Dim lastRow As Long
Dim i As Long
Dim ws As Worksheet
Dim txt As String
Set ws = Sheets("Player List")
Dim matchFoundIndex As Long
Dim iCntr As Long

lastRow = Range("A201").End(xlUp).Row
For iCntr = 1 To lastRow
    If Cells(iCntr, 1) <> "" Then
        matchFoundIndex = WorksheetFunction.Match(Cells(iCntr, 1), Range("A1:A" & 
        lastRow), 0)
        If iCntr <> matchFoundIndex Then
            Cells(iCntr, 2) = "Duplicate"
        End If
    End If
Next

The loop with the msgbox:

For i = 2 To 201
    If ws.Range("B" & i).Value = "Duplicate" Then
        txt = "Duplicates found for" + " " + ws.Range("A" & i).Value + " " + "in" + 
            ws.Range("L" & i).Value + vbNewLine
        End If
    Next i
MsgBox txt

Solution

  • You need to persist the old value of txt.

    txt = txt & "Duplicates found for" & " " & ws.Range("A" & i).Value & " " & "in" & ws.Range("L" & i).Value & vbNewLine