Converti matrice in vettore - Esempi di codice VBA

Converti matrice in un vettore

Questo è il tutorial opposto del tutorial Conversione di un vettore a riga singola in una matrice.

La seguente funzione prenderà un intervallo come matrice e lo convertirà in un vettore a colonna singola:

Opzione Funzione esplicita Create_Vector(Matrix_Range As Range) As Variant Dim No_of_Cols As Integer, No_Of_Rows As Integer Dim i As Integer Dim j As Integer Dim Cell No_of_Cols = Matrix_Range.Columns.Count No_Of_Rows (No_Of_Rows) = No_Of_Rows_Reim.Rows 'Elimina le condizioni NULL se Matrix_Range non è nulla, quindi esci dalla funzione If No_of_Cols = 0 Quindi esci dalla funzione If No_Of_Rows = 0 Quindi esci dalla funzione For j = 1 To No_Of_Rows For i = 0 To No_of_Cols - 1 Temp_Array((i * No_Of_Rows) + j) = Matrix_Range.Cells(j, i + 1) Next i Next j Create_Vector = Temp_Array End Function

Quindi ad esempio il vettore:

Diventerà:

Dove abbiamo usato la seguente subroutine per stampare il vettore:

Private Sub CommandButton1_Click() Dim Vector Dim k As Integer Vector = Create_Vector(Sheets("Sheet1").Range("A4:D8")) For k = 1 To UBound(Vector) Sheets("Sheet1").Range(" B20"). Offset(k, 1).Value = Vector(k) Next k End Sub

Nota che queste routine funzionano sia sui numeri che sul testo.

Per scaricare il file .XLSM da questo tutorial, fai clic qui.

wave wave wave wave wave