将数组变量的所有元素放在消息框中的各自行上

时间:2013-09-03 15:42:16

标签: arrays vba msgbox

下面的代码是我写的一个宏的片段,用于提醒用户他们在订单上可能没有足够数量的兼容安装设备。 n个缺陷(即,没有兼容安装设备的设备项目的每个实例都保存在元素1到n的yankees()数组中。我想要做的是提示用户输入一个消息框,说明“请检查您的订单以确保你有足够的兼容安装设备 - 我们发现了以下不足之处“

及以下

将所有yankees元素(1到n)包含在消息框中的不同行中,下面有两个选项“这没关系,我现在就提交订单”和“让我回去,我想修改我的令”。

如何创建这样的消息框?

我有:

 MsgBox "Please review your order to ensure you have you sufficient compatible     installation equipment- we detected the following concerns" & yankee(1), vbOKCancel

目前但这仅包括第一次缺口。如何包含yankee()的所有元素并将它们放在自己的行上?

这个问题实际上归结为:“如何在消息框提示符中将数组变量的所有非空元素放在自己的行上?”

Do
If rip(qbert) < k(qbert) Then
yankee(jets) = "Your order for" & s(qbert) & " contains " & k(qbert) - rip(qbert) & " too     few " & g(qbert)
jets = jets + 1
qbert = qbert + 1
Else
qbert = qbert + 1
End If
Loop Until qbert > echo

2 个答案:

答案 0 :(得分:5)

您可以使用Join功能:

Sub Test()
    Dim var As Variant

    'Populate a dummy vector array from a comma-separated list:
    var = Split("Alpha,Beta,Gamma,Delta,Epsilon", ",")

    'Display the contents of the array as delimited list, use the Carriage Return to delimit:
    MsgBox Join(var, vbCR)

End Sub

enter image description here

以上不会忽略空白。要忽略空白,根据您的具体问题,您可以迭代数组并测试空值。我会在Function

中执行此操作

如何在消息框提示中将数组变量的所有非空元素放在各自的行中

在您的子广告中,只需将yankees传递给此函数,例如:

MsgBox = GetMessageText(yankees)

这是功能:

Function GetMessageText(var As Variant) As String
    'Assumes a vector array
    On Error GoTo EarlyExit

    Dim sMsg As String
    Dim v As Variant

    For Each v In var
        If Not v = vbNullString Then
            sMsg = sMsg & v & vbCr
        End If
    Next

EarlyExit:
    If Err.Number = 0 Then
        GetMessageText = sMsg
    Else:
        GetMessageText = "invalid array"
    End If

End Function

答案 1 :(得分:2)

替代:

Sub tgr()

    Dim yankee(1 To 5) As String
    Dim strMsg As String

    yankee(1) = "Did this"
    yankee(3) = "experiment"
    yankee(5) = "really work?"

    'yankee => ["Did this", , "experiment", , "really work?"] _
     the yankee array has two blanks at positions 2 and 4 _
     and it also has spaces in some of the element strings

    strMsg = Replace(Replace(WorksheetFunction.Trim(Replace(Replace(Join(yankee, "|"), " ", "_"), "|", " ")), " ", vbCrLf), "_", " ")

    'strMsg => "Did this _
                experiment _
                really work?"

    'Yes it did, see result
    MsgBox strMsg

End Sub