简体   繁体   中英

vba loop through array, store values to arrayi

I have some data, stored in arrays like

Dim arrA, arrB, arrC, arrAi, arrBi
Dim i as integer, x as integer

for i = 1 to 100

    if cells(i,1).value = "criteria" then ' just add value to array when it meets some criteria
        x = x + 1
        arrA(x) = cells(i,1).value
        arrB(x) = cells(i,2).value
        arrC(x) = cells(i,3).value
    end if

next i

redim preserve arrA(1 to x)
redim preserve arrB(1 to x)
redim preserve arrC(1 to x)

And the data looks like

arrA: 26.1 40.2 80.3 26.0 41.3 78.7 25.8 40.8 80.0

arrB: 10 11 10 66 67 64 32 32 33

arrC: 1 2 3 1 2 3 1 2 3

Since the values in arrA 26.1, 26.0, 25.8 (position 1, 4, 7) belong to group 1 (referencing to values in arrC at same position), I would like to store 26.1 26.0 25.8 to arrAi and 10 66 32 to arrBi for subsequent calculations.

How can I loop through the 3 arrays and store values to another array as described above?

Thanks in advance.

Try the next way, please:

Sub handleArraysFromArrays()
 'your existing code...
 'but you fistly must declare
  Dim arrA(1 To 100), arrB(1 To 100), arrC(1 To 100)
 '....
 'your existing code
 '...
 Dim k As Long, kk As Long
 
 ReDim arrAi(1 To UBound(arrA))
 ReDim arrBi(1 To UBound(arrA))
 For i = 1 To UBound(arrC)
    If arrC(i, 1) = 1 Then k = k + 1: arrAi(k, 1) = arrA(i, 1)
    If arrC(i, 1) = 2 Then kk = kk + 1: arrBi(kk, 1) = arrA(i, 1)
 Next i
 ReDim Preserve arrAi(1 To k): ReDim Preserve arrBi(1 To kk)
 Debug.Print UBound(arrAi), UBound(arrBi)
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM