transpose函数的功能是将数组转置,如果你的数组是一维(默认的一维数组是一行),转置后成为一列,转置的也不一定非得是一维数组,多维也可以。
下面为大家介绍VBA中如何使用Transpose。
简单应用:
Dim arr(1 To 10)
For i = 1 To 10
arr(i) = Cells(i, 1)
Next
Range("b1").Resize(UBound(arr)) = Application.Transpose(arr)
稍微复杂的应用:
Option Explicit
Dim arr, brr, d, i, nr, nc
Set d = CreateObject("Scripting.Dictionary")
With Sheet2
nr = .Range("A65536").End(xlUp).Row
nc = 3
arr = .[A1].Resize(nr, nc)
End With
For i = 1 To UBound(arr)
If Not d.Exists(arr(i, 3)) Then
d.Add arr(i, 3), arr(i, 1)
Else
If InStr(d(arr(i, 3)), arr(i, 1)) = 0 Then
d(arr(i, 3)) = d(arr(i, 3)) & "," & arr(i, 1)
End If
End If
Next i
Sheet3.Range("A:E").ClearContents
arr = Application.WorksheetFunction.Transpose(d.keys)
brr = d.items
ReDim Preserve arr(1 To UBound(arr), 1 To 2)
For i = 1 To UBound(arr)
arr(i, 2) = brr(i - 1)
Next
Sheet3.Range("A1").Resize(UBound(arr), UBound(arr, 2)) = arr
Set d = Nothing
Set arr = Nothing
Set brr = Nothing