VBA - 剪切每行的最后一个条目并粘贴到新列中。行的长度变化

VBA - Cut the last entry from each row and paste into a new column. Length of rows varies

我是新用户,还不能嵌入图片...请查看链接。

假设我的数据是这样的:Before. And, I'd like it to look like this: After。这是我一直在尝试(未成功)的代码:

Dim lastRow As Long
lastRow = Range("Sheet2!A" & Rows.Count).End(xlUp).Row
Dim col As Integer
col = Range("Sheet2!A1:A" & lastRow).End(xlToRight).Column
Columns(col).Copy
Columns(col + 1).Insert Shift:=xlToRight

我希望宏能够处理具有任意行数的数据集,因此是 lastRow 的东西。有什么想法吗?

这个工作怎么样?

Sub move_data()
Dim lastRow As Long, lastCol As Long
Dim ws As Worksheet

Set ws = Worksheets("Sheet2")
lastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
lastCol = ws.UsedRange.Columns.Count

Dim i As Long
For i = 1 To lastRow
    If ws.Cells(i, lastCol) = "" Then
        ws.Cells(i, ws.Cells(i, 1).End(xlToRight).Column).Cut ws.Cells(i, lastCol)
    End If
Next i

End Sub

我对使用 UsedRange 犹豫不决,但如果您的数据确实存在于 "block" 中,那应该没问题。基本上,它只是检查每一行,如果最后一列为空,则将最后一个单元格从 A 列移动到该列。