VBA:将下方的值移至空单元格

VBA: Move values below to emptied cell

我有这个子程序可以连续清除值:

Sub ClearRow_Click()
    Dim currRow As Long
    currRow = ActiveCell.Row

    If currRow >= 5 And currRow <= 300 Then
        Range("A" & currRow).ClearContents
    End If

End Sub

注意:currRow 是被清除的行。

我想要做的是包含一段代码,它将移动 A 列中的所有后续值(长度到第 300 行),从 currRow (currRow + 1) 之后的下一行开始进入 currRow。所以在清除一行之后,我们有这个:

Column A
1111

3333
4444

然后我希望代码在之后执行此操作:

Column A
1111
3333
4444

我试过 .End(xlDown)Selection.cut 但由于剪切而出现引用错误,因为我有其他列引用 A,例如在 B2 中我有:

=IF(A2<>"", $B, "")

并将此结果提交给#REF!当我四处移动单元格时出现错误和格式更改。

这有点蛮力,但我认为它能满足您的需求。

假设您的数据列在 A:J 列中,并且您想要 shift 所有行中的值 beneath ] ActiveCell,向上一行(有效地将 ActiveRow 替换为

Option Explicit
Dim rng As Range
Dim shiftRng As Range

Sub ClearRow_Click()
    Dim currRow As Long
    Dim rng As Range
    Dim rngShift As Range

    currRow = ActiveCell.Row
    'This is the full range of data
    If rng Is Nothing Then Set rng = Range("A5:J300")

    'This gets the next n rows to the last row of your range
    If rngShift Is Nothing Then Set rngShift = Range("A" & (ActiveCell.Row + 1) & ":J300")

    If currRow >= 5 And currRow <= 300 Then
       '# This copies ONLY column A and moves the values up one row
       '  This will leave intact all of the rest of the data in columns B:J, etc.
       '  This preserves formatting -- essentially it just moves the values
        rngShift.Columns(1).Offset(-1).Value = rngShift.Columns(1).Value
        '# Get rid of the value in the last row, since it's been shifted up
        Range("A300").ClearContents
    End If
End Sub