VBA - 从每行中剪切最后一个条目并粘贴到新列中.行的长度各不相同



我是新用户,还不能嵌入图像...请参阅链接。

假设我的数据如下所示:以前。而且,我希望它看起来像这样:之后。这是我一直在尝试的代码(不成功(:

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,但是如果您的数据确实存在于"块"中,那么应该可以正常工作。 基本上,它只是检查每一行,如果最后一列为空,则将最后一个单元格从 A 列移动到该列。

最新更新