Excel将行复制到空白单元格

时间:2015-07-30 13:03:29

标签: excel vba excel-vba

如果单元格为空,我试图将包含数据的行(在单元格A,B,C,D中)向下复制到相同的单元格(在不同的行中)。因此,如果前面的单元格为空,则基本上复制上述单元格中的数据。我的代码如下:

Sub PadOut()
With Range("A2:D300") ' change this
  On Error Resume Next
  Set aRange = .SpecialCells(xlCellTypeBlanks)  'check for blank cells
  On Error Goto 0
  If Not aRange Is Nothing Then   
     aRange.FormulaR1C1 = "=R[-1]C"   
     .Value = .Value   
  End If
End With
End Sub

目前我在设定范围内有它..但是如何设置以便可以扩展范围(如果我不知道总行数)

4 个答案:

答案 0 :(得分:1)

这是你想要达到的目标吗?您可以根据需要更改起始行和列号。 endCol变量定义要扫描的最后一个colulmn,endRow循环查找定义的列范围中最后一个使用的行。

Sub PadOut()

    Application.ScreenUpdating = False

    Dim startRow As Long
    startRow = 2
    Dim startCol As Long
    startCol = 1
    Dim endCol As Long
    endCol = 3

    With ActiveSheet

        Dim row As Long
        Dim col As Long
        Dim endRow As Long

        Dim bottomRow As Long
        bottomRow = ActiveSheet.Rows.Count
        Dim colEndRow As Long
        endRow = 0
        For col = startCol To endCol
            If (Cells(bottomRow, col).End(xlUp).row > endRow) Then
                endRow = Cells(bottomRow, col).End(xlUp).row
            End If
        Next col

        For col = startCol To endCol
            For row = startRow + 1 To endRow
                If .Cells(row, col).value = "" Then
                    .Cells(row, col).value = .Cells(row - 1, col).value
                End If
            Next row
        Next col

    End With

    Application.ScreenUpdating = True

End Sub

答案 1 :(得分:1)

Sub PadOut()
lastRow = ActiveSheet.UsedRange.Rows.Count
if cells(lastRow, 1) = "" and cells(lastRow, 2) = "" and cells(lastRow, 3) = "" and cells(lastRow, 4) = "" then
  lastRow = WorksheetFunction.Max(cells(lastRow, 1).end(xlup).row, cells(lastRow, 2).end(xlup).row, cells(lastRow, 3).end(xlUp).row, cells(lastRow, 4).end(xlup).row)
end if

With Range("A2:D" & lastRow)
  On Error Resume Next
  Set aRange = .SpecialCells(xlCellTypeBlanks)  'check for blank cells
  On Error Goto 0
  If Not aRange Is Nothing Then   
     aRange.FormulaR1C1 = "=R[-1]C"   
     .Value = .Value   
  End If
End With
End Sub

答案 2 :(得分:0)

您可以使用以下方法获取总行数:

numberRows = ActiveSheet.UsedRange.Rows.Count

然后您可以相应地设置范围。

答案 3 :(得分:0)

你真的不需要VBA来完成这项任务。 可以使用选择页面和数组填充来完成。

要做到这一点: 突出显示您的范围,从您有兴趣填充空白数据的第一行和单元格开始。 接下来,按CTRL + G ,这将显示“转到”窗口,按特殊... 选择“空白”选项,然后按确定。 这将选择您范围内的所有BLANK单元格。然后,不点击(或者您将更改您的选择),键入: = {按向上箭头}然后按CTRL + ENTER

您之前的数据 // 您的数据

之后

enter image description here enter image description here

相关问题