我的数据看起来像这样......
a 1 c 3 e 5
b 2 d 4 f 6
我想在VBA中编写一个脚本将其转换为...
a 1
b 2
c 3
d 4
e 5
f 6
换句话说,每两列将堆叠成两列新列 以下代码适用于单个列...如何让它适用于两个列? 例如,有没有办法运行两次...每个字母列一次,然后再为每个编号列运行一次?或者也许是一种更清洁的方式?
Sub StackColumns()
Dim X As Long, LastColumn As Long
LastColumn = Cells.Find(What:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column
For X = 1 To LastColumn
Columns(X).Resize(Cells(Rows.Count, X).End(xlUp).Row).Copy _
Cells(Rows.Count, LastColumn + 1).End(xlUp).Offset(-(X > 1))
Next
On Error Resume Next
Columns(LastColumn + 1).SpecialCells(xlBlanks).Delete xlShiftUp
End Sub`
答案 0 :(得分:1)
答案 1 :(得分:0)
对于未来的观众,我最终运行了两次这个命令。
Sub StackColumns()
Dim X As Long, LastColumn As Long
LastColumn = Cells.Find(What:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column
For X = 1 To LastColumn Step 2
Columns(X).Resize(Cells(Rows.Count, X).End(xlUp).Row).Copy _
Cells(Rows.Count, LastColumn + 1).End(xlUp).Offset(-(X > 1))
Next
On Error Resume Next
Columns(LastColumn + 1).SpecialCells(xlBlanks).Delete xlShiftUp
End Sub
然后:
Sub StackColumns()
Dim X As Long, LastColumn As Long
LastColumn = Cells.Find(What:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column
For X = 2 To LastColumn Step 2
Columns(X).Resize(Cells(Rows.Count, X).End(xlUp).Row).Copy _
Cells(Rows.Count, LastColumn + 1).End(xlUp).Offset(-(X > 1))
Next
On Error Resume Next
Columns(LastColumn + 1).SpecialCells(xlBlanks).Delete xlShiftUp
End Sub