4

我有一张数据混乱的 Excel 表:例如,应该在 AB 列和 AC 列中的数据在 B 列和 C 列中,但在后面的行中。我写了以下内容,分别将数据从 B 和 C 移动到 AB 和 AC:

Dim rCell As Range
Dim rRng As Range

Set rRng = Sheet1.Range("A:A")

i = 1

lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row

For Each rCell In rRng.Cells

If rCell.Value = "" Then

    Range("AB" & i) = rCell.Offset(0, 1).Value

    rCell.Offset(0, 1).ClearContents

    End If

    i = i + 1

    If i = lastRow + 1 Then

    Exit Sub

    End If

Next rCell

End Sub

但是,它不能解决数据位于相应行下方的问题,因为它们位于正确的列中。我是 VBA 宏的新手,所以我将不胜感激任何帮助以使数据现在对齐。我尝试切换 Offset 参数 (-1,0) 但它不起作用。

4

2 回答 2

1

试试这样的东西?

For i = Lastrow To 1 Step -1
    ' move data into cell AA from Cell A one row down
    Cells(i, 27).Value = Cells(i + 1, 1).Value
Next
于 2012-10-30T20:11:30.913 回答
0

您无需遍历范围即可完成您想要做的事情。

试试这个:

Sub MoveBCtoAbAcUpOneRow()
    Dim firstBRow As Integer
    Dim lastBRow As Long
    Dim firstCRow As Integer
    Dim lastCRow As Long

    ' get the first row in both columns
    If Range("B2").Value <> "" Then
        firstBRow = 2
    Else
        firstBRow = Range("B1").End(xlDown).Row
    End If
    If Range("C2").Value <> "" Then
        firstCRow = 2
    Else
        firstCRow = Range("C1").End(xlDown).Row
    End If

    ' get the last row in both columns
    lastBRow = Range("B" & ActiveSheet.Rows.Count).End(xlUp).Row
    lastCRow = Range("C" & ActiveSheet.Rows.Count).End(xlUp).Row

    ' copy the data to the correct column, up one row
    Range("B" & firstBRow & ":B" & lastBRow).Copy Range("AB" & firstBRow - 1)
    Range("C" & firstCRow & ":C" & lastCRow).Copy Range("AC" & firstCRow - 1)

    ' clear the incorrect data
    Range("B" & firstBRow & ":B" & lastBRow).ClearContents
    Range("C" & firstCRow & ":C" & lastCRow).ClearContents

End Sub

笔记:

  • 如果每一列中数据的形状相同,则不需要为每一列查找第一行和最后一行。每个变量只需要一个变量,一个复制操作而不是 2 个。
  • 确保将变量声明设置为必需。(工具 -> 选项 -> 需要变量声明)您可能已经这样做了,但我不知道,因为它看起来像您的 Sub 的顶部被截断了。
于 2012-10-30T22:53:15.267 回答