Vba 创建宏以向上移动列中的数据?

Vba 创建宏以向上移动列中的数据?,vba,excel,excel-2010,Vba,Excel,Excel 2010,我有一个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

我有一个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宏的新手,因此希望您能帮助我对齐数据。我尝试切换偏移参数(-1,0),但它不起作用。

是否尝试类似的操作

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

你不需要在整个范围内循环来完成你想要做的事情

请尝试以下方法:

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
子移动bctoabacuponerow()
将firstBRow设置为整数
黯淡的眉头
将firstCRow设置为整数
乌鸦一样长
'获取两列中的第一行
如果范围(“B2”)。值为“”,则
firstBRow=2
其他的
firstBRow=范围(“B1”)。结束(xlDown)。行
如果结束
如果范围(“C2”).值为“”,则
firstCRow=2
其他的
firstCRow=范围(“C1”)。结束(xlDown)。行
如果结束
'获取两列中的最后一行
lastBRow=范围(“B”&ActiveSheet.Rows.Count).End(xlUp.Row)
lastCRow=Range(“C”&ActiveSheet.Rows.Count).End(xlUp).Row
'将数据复制到正确的列,最多一行
范围(“B”&firstBRow&“:B”&firstBRow)。复制范围(“AB”&firstBRow-1)
范围(“C”&firstCRow&“:C”&lastCRow)。复制范围(“AC”&firstCRow-1)
“清除不正确的数据
范围(“B”和“firstBRow&“:B”和“lastBRow”).ClearContents
范围(“C”&firstCRow&“:C”&lastCRow)。ClearContents
端接头
注意事项:

  • 如果每列中的数据形状相同,则不需要 找到每一行的第一行和最后一行。每个操作只需要一个变量和一个复制操作,而不是2个
  • 确保将变量声明设置为必需。 (工具->选项->要求变量声明)您可能已经在执行此操作,但我无法确定,因为它看起来像是子对象的顶部被截断了