Msgbox With If statement

3.2k views Asked by At

I'm trying to get a box to pop up listing a number of values that could be blank.

MsgBox (res1 & vbNewLine & _
res2 & vbNewLine & _
res3 & vbNewLine & _
res4 & vbNewLine & _
res5 & vbNewLine & _
res6 & vbNewLine & _
res7 & vbNewLine & _
res8 & vbNewLine & _
res9 & vbNewLine & _
res10 & vbNewLine & _
res11 & vbNewLine & _
res12 & vbNewLine)

what I want to do is have is something like this:

if res1 <> "" then
    res1 & vbNewLine 
else
    ""
end if

Because what shows at the moment is load of blank lines:

https://i.stack.imgur.com/M4PZf.png

3

There are 3 answers

1
PaulFrancis On BEST ANSWER

You could declare a String, and construct the string to display the characters. Something like,

Dim tmpRes As String

If Len(res1) > 0 Then _
    tmpRes = tmpRes & res1 & vbCrLf 

If Len(res2) > 0 Then _
    tmpRes = tmpRes & res2 & vbCrLf

If Len(res3) > 0 Then _
    tmpRes = tmpRes & res3 & vbCrLf

If Len(res4) > 0 Then _
    tmpRes = tmpRes & res4 & vbCrLf

If Len(res5) > 0 Then _
    tmpRes = tmpRes & res5 & vbCrLf

If Len(res6) > 0 Then _
    tmpRes = tmpRes & res6 & vbCrLf

If Len(res7) > 0 Then _
    tmpRes = tmpRes & res7 & vbCrLf

If Len(res8) > 0 Then _
    tmpRes = tmpRes & res8 & vbCrLf

If Len(res9) > 0 Then _
    tmpRes = tmpRes & res9 & vbCrLf

If Len(res10) > 0 Then _
    tmpRes = tmpRes & res10 & vbCrLf

MsgBox tmpRes
0
NicolaSysnet On

If you don't want to make the string outside the msgbox function call you can use an inline if:

MsgBox (res1 & Iif(res1<>"", vbNewLine, "") & _
res2 & Iif(res2<>"", vbNewLine, "") & _
res3 & Iif(res3<>"", vbNewLine, "") & _
res4 & Iif(res4<>"", vbNewLine, "") & _
res5 & Iif(res5<>"", vbNewLine, "") & _
res6 & Iif(res6<>"", vbNewLine, "") & _
res7 & Iif(res7<>"", vbNewLine, "") & _
res8 & Iif(res8<>"", vbNewLine, "") & _
res9 & Iif(res9<>"", vbNewLine, "") & _
res10 & Iif(res10<>"", vbNewLine, "") & _
res11 & Iif(res11<>"", vbNewLine, "") & _
res12 & Iif(res12<>"", vbNewLine, "") )
0
RubberDuck On

Good grief everyone is making this harder than it has to be...

Store all of your string variables in an array, and then create a BuildMessage function that takes in the array, and then loops over it, returning the final message.

Public Sub Test()

    Const res1 As String = vbNullString
    Const res2 As String = "Hello"
    Const res3 As String = vbNullString
    Const res4 As String = "GoodBye"
    Const res5 As String = vbNullString

    Dim resArr As Variant
    resArr = Array(res1, res2, res3, res4, res5)

    Dim msg As String
    msg = BuildMessage(resArr)

    MsgBox msg

End Sub

Private Function BuildMessage(ByVal arr As Variant) As String

    Dim msg As String

    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        Dim str As String
        str = arr(i)

        If str <> vbNullString Then
            msg = msg & str & vbNewLine
        End If
    Next

    BuildMessage = msg

End Function