Msgbox With If语句

时间:2015-06-17 12:24:46

标签: vba excel-vba excel-2003 excel

我正在尝试弹出一个框,列出一些可能为空的值。

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)

我想要做的就是这样:

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

因为此时显示的是空白行的加载:

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

3 个答案:

答案 0 :(得分:3)

好悲伤每个人都在努力做到这一点......

将所有字符串变量存储在一个数组中,然后创建一个接收数组的BuildMessage函数,然后遍历它,返回最后的消息。

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

答案 1 :(得分:1)

如果您不想在msgbox函数调用之外创建字符串,则可以使用内联:

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, "") )

答案 2 :(得分:0)

您可以声明一个String,并构造字符串以显示字符。像,

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