Search code examples
excelvbamatrixvector

How to create a matrix using a repeated vector in VBA?


I have the following vector in vba:

If Blad1.Range("number").Value < 1 Then
        n = 1
Else
        n = Blad1.Range("number").Value
End If

curve = Blad2.Range(Cells(1, 3), Cells(1, 3 + n - 1)).Value

And now I want to create a matrix in which the vector "curve" is repeated n times, that is, every row is the same. Is this possible in vba?


Solution

  • Using a 2D array. This assumes that n is a positive integer.

    When n equals 1, curve is not an array, and needs to be handled slightly differently.

    Dim matrix As Variant
    ReDim matrix(1 To n, 1 To n)
    
    Dim i As Long, j As Long
    For i = LBound(matrix, 1) To UBound(matrix, 1)
        For j = LBound(matrix, 2) To UBound(matrix, 2)
            If n = 1 Then
                matrix(i, j) = curve ' curve is not an array
            Else
                matrix(i, j) = curve(1, j)
            End If
        Next
    Next 
    

    Side note:

    curve = Blad2.Range(Cells(1, 3), Cells(1, 3 + n - 1)).Value
    

    can be simplified (and improved) to:

    curve = Blad2.Cells(1, 3).Resize(, n).Value