Excel将行复制到空白单元格

我试图复制包含数据(在单元格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 

目前,我已经在一个设定的范围..但我怎么可以设置,以便范围可以扩大(如果我不知道总行数)

这是你想要实现的吗? 您可以根据需要更改开始行和列号。 endColvariables定义要扫描的最后一个endRow循环find定义的列范围中最后一个使用的行。

 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 
 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 

您可以使用以下命令获取总行数:

 numberRows = ActiveSheet.UsedRange.Rows.Count 

那么你可以相应地设置范围。

你并不需要VBA来完成这个任务。 这可以使用select页面和数组填充来完成。

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

你的数据在你的数据之前

在这里输入图像说明 在这里输入图像说明