2017-07-25 158 views
1

我在一行上有3個信息,我可以選擇多行。所以我在尋找的是將每一行的第一次分割成數組的方法。將字符串拆分爲矩陣vba

這就是我在這裏做的。 線=斯普利特(MSG「」)

然後我想,每行拆分信息得到一基質與第一IDENTIFER線和第二個是信息

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

但它扔我不匹配的錯誤,所以我不知道該怎麼辦呢

例如:

我有這個

MSG1/1250 /說明,MSG 2/1500/DESCR iption2,msg3,45656,Desctiption3

終於有這樣的:

親(0,0)= MSG1

親(0,1)= 1250

親(1,1) = 1500 等等

謝謝

+0

你能舉出更多的例子嗎,沒有'etc'? – Vityata

回答

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我跳過它。

+1

謝謝我想我會把你的例子放在我的程序中,我真的很友善 –

+0

@LoPCastro - 歡迎您隨時將我的答案標記爲已接受。 – Vityata

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 
+0

如果您刪除'+ 1'並將'ReDim pro(RowCount,3)'更改爲'ReDim pro(RowCount,2)',您的解決方案會更好。目前,您在矩陣的行和列中都有空值。但仍然足夠:) – Vityata

+1

隨着Vityala修復它與我工作正常謝謝 –

1

最初作爲pro被稱爲「鋸齒陣列」。您可以使用「雙轉置」將其轉換爲二維數組。但要注意,它需要所有的「行陣」是同樣大小的:

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 
+0

謝謝,我沒有想到它是與我的數組的類型有關,我甚至不知道你可以轉置數組,以轉換他們 –