VBA:将多行字符串分割成带有字典的列表

时间:2018-08-27 08:55:22

标签: arrays vba dictionary

大家好,

我遇到以下问题:我有一个多行字符串,并且想将其拆分为带有字典的列表。

例如,我有以下字符串:

input = "Bla Bla2 Bla3" & vbLf & "Bla21 Bla22 Bla23"

我想将其拆分为一个数组,其中每个条目包含1行(即,第一个条目的第一行,依此类推)。条目本身应该是字典,其中每一列(用“”分隔的单词)由一个单词定义。

作为示例,这里有“ col1”,“ col2”和“ col3”。

结果应为包含2个元素的列表-每个元素应为字典,其中d(“ col1”)的第一个条目包含“ Bla”,第二个条目包含“ Bla21”。

我能够拆分字符串并通过拆分输入将例如第一列输入最终数组

    ar = Split(input,vbLf,,vbTextCompare)
    pos = 0

然后插入该数组-将条目动态添加到结果数组。

    Do while pos < UBound(ar)
       line = Split(ar(pos))
       if Len(Join(result)) = 0 Then
           ReDim Preserve result(0)
       else
           ReDim Preserve result(Ubound(result)+1)
       result(Ubound(result)) = line(0)
       pos = pos + 1
   Loop

现在-我的问题是针对所有列进行通用化-即将字典集成到其中。

我在“ line = Split ...)”下面添加了初始化新字典的步骤

 Set d = New dictionary

然后直接在if子句下方设置值

 d("col1") = line(0)
 d("col2") = line(1)
 d("col3") = line(2)

最后,我想将数组元素设置为与此字典相等:

result(Ubound(result)) = d

但是,这不起作用。像这样运行时,出现“参数不可选”错误。添加集合时,即:

Set result(Ubound(result)) = d

我收到“需要对象”错误。

有人可以帮助我解决此错误吗?

谢谢您的问候。

/ edit:为了使生活更轻松,这是我当前正在使用的实际功能:

Function IterateString(text as String)
      Dim pos as Integer
      Dim entry() as String
      Dim line() as String
      Dim result() as String
      Dim MyDict as Scripting.Dictionary

      entry = Split(text,vbLf,,vbTextCompare)
      pos = 0
      result = Array()

      Do While pos < Ubound(entry)
        If Trim$(entry(pos)) <> "" Then
           line = Split(entry(pos))
           Set MyDict = New Scripting.Dictionary
           If Len(Join(result)) = 0 Then
              ReDim result(0,0)
           Else
              ReDim Preserve result(UBound(result,1) + 1)
           End If
           MyDict.Add "col1",line(0)
           MyDict.Add "col2",line(1)
           Set result(Ubound(result,1)) = MyDict
        End If
        pos = pos + 1
     Loop
     IterateString = result
End Function

0 个答案:

没有答案
相关问题