我有一个包含多个行和列的 Excel 表,如下所示:
1 2 3
4 5 6
7 8 9
我需要编写宏,它将我的所有数据转换为一列并将其放入sheet2
1
2
3
4
5
6
7
8
9
我在这个网站上找到了一个公式,可以满足你的要求: http ://www.cpearson.com/excel/TableToColumn.aspx
Sub Macro1()
Dim StartTable As Range ' The original table of data
Dim RNdx As Long ' Row index
Dim CNdx As Long ' Column index
Dim TabeRowIndex As Long ' Row number of Range("StartTable")
Dim TableColumnIndex As Long ' Column number of Range("StartTable")
Dim N As Long ' Index into ColumnData
Dim WS As Worksheet ' Worksheet reference
'''''''''''''''''''''''''''
' Initialize the variables.
'''''''''''''''''''''''''''
Set ColumnData = Range("ColumnData")
Set StartTable = Range("StartTable")
TabeRowIndex = Range("StartTable").Row
TableColumnIndex = Range("StartTable").Column
Set WS = Worksheets("Sheet1")
N = 0
''''''''''''''''''''''''''''''''''''''
' Loop across then down filling
' cells with element N of ColumnData.
''''''''''''''''''''''''''''''''''''''
For RNdx = TabeRowIndex To (TabeRowIndex + (StartTable.Rows.Count))
For CNdx = TableColumnIndex To TableColumnIndex + StartTable.Columns.Count - 1
N = N + 1
ColumnData.Cells(N, 1) = WS.Cells(RNdx, CNdx).Value
Next CNdx
Next RNdx
End Sub
使用公式的替代答案sheet2
:(
您的列数为 3 - 您可以更改它)
=INDIRECT(CONCATENATE("'Sheet1'!"; ADDRESS(FLOOR(ROW()-1; 3)/3+1; MOD(ROW()-1; 3)+1)))