消息框中的VBA显示集合 - 错误

时间:2017-09-20 19:20:18

标签: vba excel-vba excel

我正在尝试弹出类似的消息,

"There are 3 Reports available . They are Today, Yesterday, Day before"

这是代码,

  On Error Resume Next
  For Each a In MonthYear
     arr.Add a, a
  Next

  For i = 1 To arr.Count
     Cells(i, 1) = arr(i)
  Next


MsgBox ("There are " & arr.Count & " Reports available. They are  " & arr &

但它不起作用。它说没有找到子或参数。

2 个答案:

答案 0 :(得分:6)

对于阵列,因为看起来OP正在使用一个。既然OP已经编辑了帖子以显示集合,那么这种方法将不起作用。

我会留给未来的读者使用数组选项。

MsgBox "There are " & UBound(arr) + 1 & " Reports available. They are  " & Join(arr,",")

答案 1 :(得分:3)

这就是我提出的:

Option Explicit

Sub TestMe()

    Dim arr     As Variant
    arr = Array("Today", "Yesterday", "DayBefore")

    MsgBox ("There are " & UBound(arr) + 1 & _
            " reports available. They are " & Join(arr, ", ") & ".")


End Sub

关于集合,这是将集合转换为字符串的一种方法:

Option Explicit

Public Sub TestMe2()

    Dim reportsCol  As New Collection
    Dim i           As Long
    Dim textReport  As String

    reportsCol.Add "Today"
    reportsCol.Add "Yesterday"
    reportsCol.Add "The day before yesterday"

    For i = 1 To reportsCol.Count
        textReport = TextReport & " " & reportsCol(i) & _
            IIf(i = reportsCol.Count, ".", ",")
    Next i

    MsgBox textReport

End Sub

底部的IIf决定是设置句号.还是逗号,