使用“偏移”在VBA中按给定顺序更改数据

我试图以特定的顺序将两列数据偏移到一行,但我无法正确设置偏移function。

我有这样的东西:

ColumnA ColumnB 1 10 2 20 3 30 4 40 5 50 

我试图从一个给定的ActiveCell中获得1行,多列,我可以select(1 10 2 20 3 30 4 40 5 50)

我的代码到目前为止是:

 Sub OffsetData1() Dim lRow As Long lRow = 0 Do lRow = lRow + 1 If IsEmpty(Cells(lRow, 2)) Then Exit Do Cells(lRow, 2).Copy ActiveCell.Offset(1, 1).PasteSpecial Loop End Sub 

任何帮助将深表谢意。

尝试下面的代码(解释在代码注释内)

 Option Explicit Sub OffsetData1() Dim lRow As Long, Col As Integer Dim RowDest As Long, ColDest As Integer ' parameters for first cell Paste, these setting are for Cell A7 RowDest = 7 ColDest = 1 For lRow = 1 To 5 ' loop through rows For Col = 1 To 2 ' loop through columns ' only copy cells with values inside If Cells(lRow, Col) <> "" Then Cells(RowDest, ColDest) = Cells(lRow, Col) ColDest = ColDest + 1 End If Next Col Next lRow End Sub 

您可以利用范围的“自然” 列举

 Option Explicit Sub main2() Dim cell As Range Dim iCol As Long For Each cell In Range("B1", Cells(Rows.Count, "A").End(xlUp)) iCol = iCol + 1 Cells(7, iCol) = cell.Value Next End Sub