2016-01-12 148 views
-2
Sub test() 
Dim strInput as String 
Dim ar2() 
Dim ar3() 
strInput = "10,20,30,40,50,60,70" 
ar1 = Split(strInput, ",") 
End Sub 

如何將ar1陣列(10,20,30,40,50,60,70)拆分爲兩個陣列,ar2 =(10,20,30,40 ,50)和ar3 =(60,70)。如何在VBA中將陣列拆分爲兩個陣列

+0

是否有分割的任何標準? –

回答

0

試試這個代碼:如果你想通過一個分割點做(好比說在這種情況下,55)

Sub Test() 
    Dim strInput As String 
    Dim IC As Long 
    IC = 5 ' Items Count in first array ar1 
    Dim ar2() 
    Dim ar3() 
    strInput = "10,20,30,40,50,60,70" 
    ar1 = Split(strInput, ",") 

    ReDim ar2(IC - 1) 
    ReDim ar3(UBound(ar1) - IC) 

    For i = 0 To IC - 1 
    ar2(i) = ar1(i) 
    Next 

    For i = 0 To UBound(ar1) - IC 
    ar3(i) = ar1(i + IC - 1) 
    Next 

'Test: 
    Debug.Print "ar2:" 
    For i = LBound(ar2) To UBound(ar2) 
    Debug.Print ar2(i) 
    Next 

    Debug.Print "======" & Chr(13) & "ar3:" 

    For i = LBound(ar3) To UBound(ar3) 
    Debug.Print ar3(i) 
    Next 


End Sub 
0

,你可以這樣做下面的下面的(我假設一切都是整數,你可以用浮點數或雙精度來做同樣的事情,但是如果你不先把它們轉換爲整數,字符串會更難一些)。要將真正爲整數的字符串轉換爲整數,只需執行CInt("10")

我設置了的樣子,你有2空數組A1和A2通過,這將填補出來:

Sub Split(A() As Integer, A1() As Integer, _ 
    A2() As Integer, Mid As Integer) 

    ' Grab the length of array A. 
    Dim Alen As Integer 
    Alen = UBound(A) 

    Dim I As Integer 
    Dim SplitIdx As Integer 
    SplitIdx = Alen 
    ' Loop through A to find out where to split it. 
    For I = 1 To Alen 
     If A(I) > Mid Then 
      SplitIdx = I - 1 
      Exit For 
     End If 
    Next I 

    ' Make sure we aren't doing anything ridiculous. 
    If SplitIdx = 0 Or SplitIdx = Alen Then 
     Exit Sub 
    End If 

    ' Now we can basically do the same thing that Fadi did. 
    ReDim A1(SplitIdx) 
    ReDim A2(Alen - SplitIdx) 

    ' Now we can just fill it out! 
    For I = 1 To Alen 
     If I <= SplitIdx Then 
      A1(I) = A(I) 
     Else 
      A2(I - SplitIdx) = A(I) 
     End If 
    Next I 
End Sub 

因此,舉例來說,使用這個,你可以這樣做以下內容:

' Recreate the array as an integer 
Dim ar1int() As Integer 
For I = 1 To 7 
    ar1int = I * 10 
Next I 

Dim ar2() As Integer 
Dim ar3() As Integer 
Call Split(ar1int, ar2, ar3, 55) 
0

或者只是這樣的:

Sub test() 
     Dim strInput As String 
     Dim ar 
     Dim ar1 
     Dim ar2 

     ' If you have some freedom to choose the text 
     strInput = "10,20,30,40;50,60,70" 
           '^ Use here some other separator 
     ar = Split(strInput, ";") 
     ar1 = Split(ar(0)) 
     ar2 = Split(ar(1)) 
    End Sub