循环以在列中查找空单元格,然后将空单元格上方的单元格复制到空单元格中

时间:2016-04-13 10:53:44

标签: vba

我在Excel中有一个超过10,000行的SAP报告。共有2列 - A& B. A是$的值,B是值的ref。 SAP报告按引用类型显示小计,但小计ref单元格B始终为空。我需要将空单元格上方的单元格复制到空单元格中(与小计相同的行)。例如A1:A5的值为3,2,3,1,1,因此小计为10,在A6中为小数。 B6中的单元格为空。 B5的ref型是12kg袋。我需要将此ref复制到Cell B6中。我这样做的原因是因为我按小计过滤报告以复制到另一个文件。目前我手动执行此操作需要很长时间。我猜它是一个循环代码,直到最后一行,因为每次运行报告时行都不同。谢谢!

1 个答案:

答案 0 :(得分:0)

这是你正在寻找的吗?此子循环遍历所有行,并检查B列中的单元格是否为空,但A列中的单元格是否包含值。如果是这样,它会将B列中的单元格从前一行复制到当前行。

 Sub fillEmptyCells()
 'copies the above cell for each empty cell in B where the cell in A is not empty
    Dim i As Integer
    Dim lastRow As Integer
    Dim ws As Worksheet
    Set ws = ActiveSheet

    lastRow = ws.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row   'This gives the last Row with a nonempty cell in column A
    For i = 1 To lastRow
        If IsEmpty(ws.Cells(i, 2)) And Not IsEmpty(ws.Cells(i, 1)) Then
            ws.Cells(i - 1, 2).Copy ws.Cells(i, 2)
        End If
    Next i
End Sub

编辑:这是与with环境相同的子

 Sub fillEmptycells()
 'copies the above cell for each empty cell in B where the cell in A is not empty
     Dim i As Integer
     Dim lastRow As Integer

     With ActiveSheet
         lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row   'This gives the last Row with a nonempty cell in column B
         For i = 1 To lastRow
             If IsEmpty(.Cells(i, 2)) And Not IsEmpty(.Cells(i, 1)) Then
                 .Cells(i - 1, 2).Copy .Cells(i, 2)
             End If
         Next i
     End With
 End Sub
相关问题