我找不到实际定义数组的方法,推送一些值并将它们作为字符串输出到VBA中? (新阵列,推送,加入)

时间:2012-10-22 13:52:59

标签: arrays vba join

我已经找到了如何创建一个数组,但我不能轻易推送项目。我必须保持下一个位置的索引,并在每次推送项目时递增;

我还发现了一个具有漂亮.Add方法的集合,其行为与push方法完全相同。但是我如何加入他们?全局Join方法不适用于集合。

我在这里缺少什么?任何人都可以帮我定义一个数组,在没有索引的情况下轻松推送项目,然后将它们输出到以“,”间隔的字符串?

由于

2 个答案:

答案 0 :(得分:10)

你不能直接这样做。 VBA中的数组通常需要在使用前进行索引和标注。

您可以在分配变量之前使用动态数组并调整大小:

Dim arr() As String
ReDim arr(0)

arr(UBound(arr)) = "Some String"
ReDim Preserve arr(UBound(arr) + 1)
arr(UBound(arr)) = "Some Other String"
ReDim Preserve arr(UBound(arr) + 1)
arr(UBound(arr)) = "Some 3rd String"

MsgBox Join(arr, ",")

保留关键字维护数组中的值而不是覆盖它们。通常不建议采用上述方法,因为Preserve价格昂贵,只允许您调整数组的最后一个维度。

在VBA环境中,集合是不同的,速度较慢且通常不太灵活(您还没有说过哪个环境,但我会假设Excel)

Dim coll As Collection
Dim itm As Variant
Dim tempS As String


Set coll = New Collection
coll.Add "Some String"
coll.Add "Some Other String"
coll.Add "Some 3rd String"

For Each itm In coll
    tempS = tempS & itm & ","
Next itm

MsgBox Left(tempS, Len(tempS) - 1)

你需要遍历它们来构建一个数组。

根据您的需求,还有许多其他选择

内置方法

对于字符串,请看看split:

Const stri As String = "Some String, Some Other String, Some 3rd String"
Dim arr() As String

arr = Split(stri, ",")

MsgBox Join(arr, ",")

使用外部对象

脚本字典

Dim dic As Object

Set dic = CreateObject("scripting.Dictionary")
dic.Add "1", "Some String"
dic.Add "2", "Some Other String"
dic.Add "3", "Some 3rd String"

Debug.Print Join(dic.items, ",")

.Net arrayList

Dim al As Object

Set al = CreateObject("System.Collections.Arraylist")
al.Add "Some String"
al.Add "Some Other String"
al.Add "Some 3rd String"

MsgBox Join(al.ToArray(), ",")

答案 1 :(得分:1)

您可以使用Collection对象,然后使用For ... Each语句循环遍历它:

Dim colItems As New Collection
Dim strOutput As String

'Add Items to Collection
colItems.Add "Item 1"
colItems.Add "Item 2"
colItems.Add "Item 3"

'Loop through the collection and place items in strOutput
For Each Item in colItems
    If strOutput <> "" Then strOutput = strOutput & ","
    strOutput = strOutput & Item
Next

Msgbox strOutput

消息框将显示Item 1,Item 2,Item3

这行代码:

If strOutput <> "" Then strOutput = strOutput & ","

是在每个项目后添加一个逗号,除了第一次循环(在添加任何项目之前)。