加入数组行或列
- 将行或列作为一维数组获取的一种简单方法是使用
Application.Index 和Application.Transpose,但有其局限性(速度慢,元素数量有限)。
- 将范围的行或列与
Application.Transpose 一起使用可能更有效。
- 最有效的方法是编写一个循环遍历二维数组的行或列并返回一维数组的函数。
- 要对此进行测试,请将代码复制到新工作簿的标准模块中,并在单元格
A1 的 Sheet1 中放置一个值表。在 VBE 立即窗口 (Ctrl+G) 中监视输出。
Option Explicit
Sub JoinArrayRowOrColumn()
Dim rg As Range: Set rg = Sheet1.Range("A1").CurrentRegion
Dim Data As Variant: Data = rg.Value ' 2D one-based array
' Join first row (note the 'double transpose').
Dim rArr As Variant: rArr = Application.Transpose( _
Application.Transpose(Application.Index(Data, 1, 0)))
Debug.Print Join(rArr, ", ")
' Join first column.
Dim cArr As Variant
cArr = Application.Transpose(Application.Index(Data, 0, 1))
Debug.Print Join(cArr, ", ")
' Without using the 'indermediate' ('Data') array (probably more efficient):
rArr = Application.Transpose(Application.Transpose(rg.Rows(1).Value))
Debug.Print Join(rArr, ", ")
cArr = Application.Transpose(rg.Columns(1).Value)
Debug.Print Join(cArr, ", ")
End Sub
一行的函数
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Returns the values of a row of a 2D array in a 1D array.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function ArrRow( _
ByVal Data As Variant, _
ByVal RowIndex As Long, _
Optional ByVal FirstIndex As Long = 0) _
As Variant
Const ProcName As String = "ArrRow"
On Error GoTo ClearError
If IsEmpty(Data) Then Exit Function
If RowIndex < LBound(Data, 1) Then Exit Function
If RowIndex > UBound(Data, 1) Then Exit Function
Dim LB2 As Long: LB2 = LBound(Data, 2)
Dim UB2 As Long: UB2 = UBound(Data, 2)
Dim cDiff As Long: cDiff = LB2 - FirstIndex
Dim rArr As Variant: ReDim rArr(FirstIndex To FirstIndex + UB2 - LB2)
Dim c As Long
For c = LB2 To UB2
rArr(c - cDiff) = Data(RowIndex, c)
Next c
ArrRow = rArr
' Debug.Print ProcName & ": [LB=" & LBound(ArrRow) _
' & ",UB=" & UBound(ArrRow) & "]"
' Debug.Print ProcName & ": [" & Join(ArrRow, ", ") & "]"
ProcExit:
Exit Function
ClearError:
Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Function
Sub ArrRowTEST()
Dim rg As Range: Set rg = Sheet1.Range("A1").CurrentRegion
' Note that if rg contains more than one (contiguous) cell,
' rg.Value is actually a 2D one-based array already.
Dim rArr As Variant: rArr = ArrRow(rg.Value, 1)
If Not IsEmpty(rArr) Then
Debug.Print Join(rArr, ", ")
End If
End Sub