将字符串拆分为矩阵vba

时间:2017-07-25 08:58:29

标签: vba matrix split

我有3行信息,我可以选择多行。所以我正在寻找的是将每行第一次分成数组的方法。

这就是我在这里做的事情。     line = Split(msg,",")

然后我想为每一行拆分信息以获得一个矩阵,首先标识该行,第二行是信息

ReDim pro(Ubound(line),3)
For i = 0 To Ubound(line)
pro(i) = Split(ligne(i), "/")
Next

但它给我一个不匹配的错误,所以我不知道该怎么做

例如:

我有这个

MSG1 / 1250 /描述,MSG2 / 1500 /内容描述,msg3,45656,Desctiption3

最后有这个:

pro(0,0)= msg1

pro(0,1)= 1250

pro(1,1)= 1500 等...

谢谢

3 个答案:

答案 0 :(得分:1)

以任何方式都不是最佳的,但它应该给你一个开始:

Dim RowCount As Integer
Dim i As Integer
Dim j As Integer
Dim x As Variant
Dim y As Variant
Line = "msg1/1250/Description,msg2/1500/Description2,msg3/45656/Desctiption3"
RowCount = UBound(Split(Line, ",")) + 1
ReDim pro(RowCount, 3)
For Each x In Split(Line, ",")
    j = 0
    For Each y In Split(x, "/")
        pro(i, j) = y
        j = j + 1
    Next y
    i = i + 1
Next x

答案 1 :(得分:1)

最初作为pro的内容称为"锯齿状阵列"。你可以使用"双转置"将其转换为2D数组。但要注意它需要所有的"线阵列"大小相同:

Function toMatrix(msg as string)
  Dim line: line = Split(msg, ",")
  ReDim pro(UBound(line))
  Dim i As Long
  For i = 0 To UBound(line)
    pro(i) = Split(line(i), "/")
  Next

  ' transform array of arrays into a 2D array.  
  toMatrix = Application.Transpose(Application.Transpose(pro))
End Function

Sub Test
  Dim msg As String
  msg = "msg1/1250/Description,msg2/1500/Description2,msg3/45656/Desctiption3"
  Dim ar
  ar = toMatrix(msg) ' ar is now a 2D array
End Sub

答案 2 :(得分:0)

我就这样做了:

Option Explicit

Public Sub TestMe()

    Dim strInput            As String

    Dim arrVals             As Variant
    Dim arrVar              As Variant
    Dim arrVar2             As Variant
    Dim arrResult           As Variant
    Dim lngCount            As Long: lngCount = 0

    strInput = "msg1/1250/Description,msg2/1500/Description2,msg3/45656/Desctiption3"
    arrVals = Split(strInput, ",")

    ReDim arrResult(UBound(arrVals), 1)

    For Each arrVar In arrVals

        arrVar2 = Split(arrVar, "/")
        arrResult(lngCount, 0) = arrVar2(0)
        arrResult(lngCount, 1) = arrVar2(1)
        lngCount = lngCount + 1

    Next arrVar

End Sub

结果是:

enter image description here

至于我没有看到你需要DescriptionN,我已经跳过了它。