有時需要在Excel中將某個多行多列的區(qū)域轉(zhuǎn)換到一列中,下面的VBA代碼可以實現(xiàn)這個目的。
1.按快捷鍵Alt+F11,打開VBA編輯器,在右側(cè)代碼窗口中粘貼下列代碼:
Sub RangeToOneCol()
Dim TheRng, TempArr
Dim i As Integer, j As Integer, elemCount As Integer
On Error GoTo line1
Range("a:a").ClearContents
If Selection.Cells.Count = 1 Then
Range("a1") = Selection
Else
TheRng = Selection
elemCount = UBound(TheRng, 1) * UBound(TheRng, 2)
ReDim TempArr(1 To elemCount, 1 To 1)
For i = 1 To UBound(TheRng, 1)
For j = 1 To UBound(TheRng, 2)
TempArr((i – 1) * UBound(TheRng, 2) + j, 1) = TheRng(i, j)
Next
Next
Range("a1:a" & elemCount) = TempArr
End If
line1:
End Sub
上述代碼可以將所選擇的區(qū)域轉(zhuǎn)換到A列中。
2.關(guān)閉VBA編輯器,返回Excel工作表界面。
3.如果A列包含數(shù)據(jù),先在工作表的最左側(cè)插入一列,以便放置轉(zhuǎn)換后的數(shù)據(jù)。
4.選擇需要轉(zhuǎn)換的區(qū)域,按Alt+F8,打開“宏”對話框,選擇上述代碼中的宏名“RangeToOneCol”運行代碼。