从@VBasic2008建议的代码开始,贴出我写的UDF函数来管理所有转置场景。
特点:
- 基于任意的阵列管理
- 在 UDF 函数的出口处不修改输入数组的基数
- 用于管理一维(单行)数组/一维(一列)数组的两个选项
Function Transpose(sAr As Variant, Optional Force2DOneRowArray As Boolean = True, Optional Force2DOneClmArray As Boolean = True) As Variant
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Transposes any-based array, manages in the right way the case of '
' 2D (one-row) array/1D array to a 2D (one-column) array and vice versa '
' Arguments: '
' - sAr Source Array '
' - Force2DOneRowArray Force function to transpose 2D matrix [n x 0]/1D (one-column) array to '
' 2D matrix [0 x n]/1D (one-row) array rather than to a simple 1D array '
' - Force2DOneClmArray Force function to transpose 2D matrix [0 x n]/1D (one-row) array to '
' 2D matrix [n x 0]/1D (one-column) array rather than to a simple 1D array '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim tAr As Variant
Dim i As Long, j As Long
On Error Resume Next
i = UBound(sAr, 2)
If Err.Number <> 0 Then '1D (one-row) array --> Vertical transpose
On Error GoTo 0
ReDim tAr(LBound(sAr) To UBound(sAr), 0)
For i = LBound(sAr) To UBound(sAr)
tAr(i, 0) = sAr(i)
Next i
Else '2D array
If i <> 0 Then
If UBound(sAr) <> 0 Then '2D matrix [n x m]
ReDim tAr(LBound(sAr, 2) To UBound(sAr, 2), LBound(sAr) To UBound(sAr))
For i = LBound(sAr, 2) To UBound(sAr, 2)
For j = LBound(sAr) To UBound(sAr)
tAr(i, j) = sAr(j, i) '2D matrix [n x m] --> 2D matrix [m x n]
Next j
Next i
Else '2D matrix [0 x n]/1D (one-row) array --> Vertical transpose
If Force2DOneClmArray Then
ReDim tAr(LBound(sAr, 2) To UBound(sAr, 2), 0)
For i = LBound(sAr, 2) To UBound(sAr, 2)
tAr(i, 0) = sAr(0, i) '2D matrix [n x 0]/1D (one-column) array
Next i
Else
ReDim tAr(LBound(sAr, 2) To UBound(sAr, 2))
For i = LBound(sAr, 2) To UBound(sAr, 2)
tAr(i) = sAr(0, i) '1D array
Next i
End If
End If
Else '2D matrix [n x 0]/1D (one-column) array --> Horizontal transpose
If Force2DOneRowArray Then
ReDim tAr(0, LBound(sAr) To UBound(sAr))
For i = LBound(sAr) To UBound(sAr)
tAr(0, i) = sAr(i, 0) '2D matrix [0 x n]/1D (one-row) array
Next i
Else
ReDim tAr(LBound(sAr) To UBound(sAr))
For i = LBound(sAr) To UBound(sAr)
tAr(i) = sAr(i, 0) '1D array
Next i
End If
End If
End If
Transpose = tAr
End Function