我只有一个包含6列10行的工作表。所以我的表的范围是A1:F10,有60个单元格。
我只需要从B列中删除数据并将其粘贴到A列中的第一个空单元格中。然后,我需要它与C - F列一样。最后我想只有一列(Column A)深60行。
Sub Move_Columns()
Range("B1:B10").Copy Destination:=Range("A11")
Range("C1:C10").Copy Desitnation:=Range("21")
' this would continue until columns B-F were copied in column A
End Sub
问题是此代码仅复制数据。我需要在复制后将其删除。我还确信有一种更有效的方式来编写代码,这样我就不必重复这些范围了。
我希望我知道如何编写代码,以便Excel自动将每列中的数据剪切并粘贴到A列的第一个空行中。
For Each Statement是否是一个好主意添加到那里?
答案 0 :(得分:0)
我制作此代码,并提供一些评论以帮助您理解。
Sub MoveAllInFirstColumn()
Dim i As Integer
Dim lastCol As Integer
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column 'finds the last column
For i = 2 To lastCol ' foreach columns except first
Dim lastRow As Integer
lastRow = Cells(Rows.Count, "A").End(xlUp).Row 'get the lastrow of current column
Range(Cells(1, i), Cells(Cells(Rows.Count, i).End(xlUp).Row, i)).Cut Cells(lastRow + 1, 1) 'cut and paste the current column to the first column
Next i
End Sub
答案 1 :(得分:-1)
继续你所拥有的:
Sub Move_Columns()
Range("B1:B10").Copy Destination:=Range("A11")
Range("B1:B10").ClearContents
Range("C1:C10").Copy Desitnation:=Range("A21")
Range("C1:C10").ClearContents
' this would continue until columns B-F were copied in column A
End Sub
带有一些循环的替代方案
Sub Move_Columns()
Dim StartCol as Integer
Dim EndCol as Integer
Dim StartRow as Integer
Dim EndRow as Integer
Dim CurRow as Integer
Dim i as Integer
Dim DestCol as integer
DestCol = 1
StartCol = 2
EndCol = 6
StartRow = 1
EndRow = 10
CurRow = StartRow
for I = StartCol to EndCol
'Range(cells(i, StartRow),cells(i, EndRow).Copy Destination:=Range(DestCol,CurRow)
'Range(cells(i, StartRow),cells(i, EndRow).ClearContents
Range(cells(StartRow, i), cells(EndRow, 1)).Copy Destination:=Range(DestCol, CurRow)
Range(cells(StartRow, i),cells(EndRow,i)).ClearContents
CurRow = CurRow + EndRow
Next
end Sub