Excel:循环遍历一行单元格并打印每一行

时间:2013-10-23 19:04:08

标签: excel loops if-statement while-loop do-while

我想在另一张纸上打印一行信息。 问题是行数总是动态的,永远不会是静态的。

例如:

*A1 = 4
*B1 = Thomas 
*C1 = Apples

*A2 = 2
*B2 = Jerry
*C2 = Oranges

*A3 = 1
*B3 = Tiffany
*C3 = Strawberries

我想要的是打印这些行以及一些字符串......

所以在第2页上启动A1

我想要阅读     A1“一定数量”& A1& “必须由”& B1& “产品将是”& C1& CHR(10)     “托马斯产品必须消耗4个苹果”(每行后新行)

我不知道如何创建一个可以执行此操作的外观,因此我不必担心行数。

1 个答案:

答案 0 :(得分:0)

不完全确定每行打印的含义。

您可以遍历列'A'中的所有值,并将下一列'D'中的值连接起来,如下所示:

Sub Macro1()
    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    Dim rRng As Range
    Set rRng = Range("A1:A" & LastRow)

    For Each cell In rRng.Cells
        cell.Offset(0, 3).Value = "A quantity of " & cell.Value & " must be consumed by " & cell.Offset(0, 1).Value & " product will be " & cell.Offset(0, 2).Value
    Next
End Sub

结果如下:

enter image description here


<强> 修改

由于你提到了一个新的行字符,我假设你出于某种原因想要一个单元格中的所有文本。试试这个:

Sub Macro1()
    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    Dim rRng As Range
    Set rRng = Range("A1:A" & LastRow)

    Dim result As Range
    Set result = Range("D1")

    result.Value = ""

    For Each cell In rRng.Cells
        result.Value = Range("D1").Value & "A quantity of " & cell.Value & " must be consumed by " & cell.Offset(0, 1).Value & " product will be " & cell.Offset(0, 2).Value & Chr(10)
    Next
End Sub

结果现在看起来像这样:

enter image description here