EXCEL VBA - 循环遍历行中的单元格,如果不为空,则将单元格值复制到另一行,直到下一行不为空

时间:2016-07-08 14:42:35

标签: excel vba excel-vba for-loop

我正在考虑编写一些代码来将行数据复制到下一行,直到下一行不为空。假设第1行中的所有内容都是标题。

数据如下:

    A2 ClientA       B2 Product1       C2 Price       D2 Quantity       E2 Cost
    A3               B3                C3 Price       D3 Quantity       E3 Cost
    A4               B4                C4 Price       D4 Quantity       E4 Cost
    A5 ClientB       B5 Product2       C5 Price       D5 Quantity       E5 Cost
    A6               B6                C6 Price       D6 Quantity       E6 Cost
    A7 ClientC       B7 Product3       C7 Price       D7 Quantity       E7 Cost
    A8               B8                C8 Price       D8 Quantity       E8 Cost
    A9               B9                C9 Price       D9 Quantity       E9 Cost

A3和A4将填写ClientA和B3,B4将填充产品,直到下一行不为空。

我搜索过一个类似的问题,但我不知道如何写它。

EXCEL VBA - Loop through cells in a column, if not empty, print cell value into another column

最终结果如下:

    A2 ClientA       B2 Product1       C2 Price       D2 Quantity       E2 Cost
    A3 ClientA       B3 Product1       C3 Price       D3 Quantity       E3 Cost
    A4 ClientA       B4 Product1       C4 Price       D4 Quantity       E4 Cost
    A5 ClientB       B5 Product2       C5 Price       D5 Quantity       E5 Cost
    A6 ClientB       B6 Product2       C6 Price       D6 Quantity       E6 Cost
    A7 ClientC       B7 Product3       C7 Price       D7 Quantity       E7 Cost
    A8 ClientC       B8 Product3       C8 Price       D8 Quantity       E8 Cost
    A9 ClientC       B9 Product3       C9 Price       D9 Quantity       E9 Cost

任何人都知道VBA代码是什么?

4 个答案:

答案 0 :(得分:2)

如果您想使用VBA,可以使用它。

我不确定你想如何找到包含数据的最后一行,所以我提供了一个你可以自己改变的变量,它对应于行。使用Z的第一个For循环将循环通过列A(1)和列B(2),在此循环内我们有另一个For循环来遍历单元格并输入最后看到的值,如果单元格值是"& #34;

Sub LoopFill()

Dim LastEntry As String, LastRow As Integer

LastRow = 25

For Z = 1 To 2
    LastEntry = ""
    For i = 1 To LastRow
        If Cells(i, Z).Value = "" Then Cells(i, Z).Value = LastEntry
        LastEntry = Cells(i, Z).Value
    Next i
Next Z

End Sub

答案 1 :(得分:2)

这是没有VBA的另一种方法。

  1. 选择空白(CTRL + G,单击特殊,选择空白,确定)
  2. 在公式栏中,键入=(直接在第一个空白区域之外) 例如:IF A2为空白,= A1
  3. 按住CTRL键,按Enter键将公式提交给所有空白单元格。
  4. 如有必要,请选择范围,复制和粘贴值以删除公式。
  5. 如果您没有粘贴值,并尝试进行排序或过滤,则数据将是错误的

答案 2 :(得分:1)

这不需要VBA。

将此公式写在辅助列中:=IF(ISBLANK(A2),F1,A2)

假设辅助列位于F列中。将其向下拖动数据集,然后将值复制到原始列中。重复B列。

答案 3 :(得分:1)

您需要:

  • SheetName:到要处理的工作表的名称

  • arColumns = Array(" A",2,3):将要填充的列号或字母添加到此数组

Sub FillRows()
    Const SheetName As String = "Sheet3"

    Dim lastRow As Long, x As Long, y
    Dim arColumns
    arColumns = Array("A", 2, 3)

    With Worksheets(SheetName)
        lastRow = .Rows(Rows.Count).End(xlUp).Row
        For x = 3 To lastRow
            For y = 0 To UBound(arColumns)
                If IsEmpty(.Cells(x, arColumns(y)).value) Then .Cells(x, arColumns(y)).value = .Cells(x - 1, arColumns(y)).value

            Next
        Next

    End With

End Sub