简体   繁体   中英

Converting 2D array to a list in VBA

I want to write a simple piece of code to calculate forces in a bolt group. the bolts are placed in a coordinate system of x columns and y rows. lets say i have a 3x4 system i get the following points:

(0,0) , (1,0) , (2,0) , (3,0)
(0,1) , (1,1) , (2,1) , (3,1)
(0,2) , (1,2) , (2,2) , (3,2)
(0,3) , (1,3) , (2,3) , (3,3)  

I can create this with the folowing code:

Dim myarray(3, 4) As String

    For x = LBound(myarray, 1) To UBound(myarray, 1)
        For y = LBound(myarray, 2) To UBound(myarray, 2)
            myarray(x, y) = x & "," & y
            Cells(x + 1, y + 1).Value = myarray(x, y)
        Next y
    Next x

now i need to get a list with x and y coordinates to calculate the vector r:

x  y  
0  0  
1  0 
2  0
3  0 
0  1
1  1
2  1
3  1
... and so on

if tried different things try and split the array, but it always fails:( any help would be greatly appreciated!

Regards,

  • Batman

Don't know where you want to put it but you can loop your current array and lengthen across 2 columns by using split on each entry

Option Explicit

Public Sub Flatten()

    Dim myarray(3, 4) As String, x As Long, y As Long

    For x = LBound(myarray, 1) To UBound(myarray, 1)
        For y = LBound(myarray, 2) To UBound(myarray, 2)
            myarray(x, y) = x & "," & y
            ActiveSheet.Cells(x + 1, y + 1).Value = myarray(x, y)
        Next y
    Next x
    
    Dim results(), r As Long, arr() As String
    ReDim results(1 To (UBound(myarray, 1) + 1) * (UBound(myarray, 2) + 1), 1 To 2)
    
    For x = LBound(myarray, 1) To UBound(myarray, 1)
        For y = LBound(myarray, 2) To UBound(myarray, 2)
            r = r + 1
            arr = Split(myarray(x, y), ",")
            results(r, 1) = arr(0)
            results(r, 2) = arr(1)
        Next y
    Next x
    
    ActiveSheet.Cells(1, 1).CurrentRegion.Offset(0, UBound(myarray, 2) + 1).Resize(UBound(results, 1), 2) = results

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