嵌套循环和组合

时间:2018-04-10 21:55:01

标签: excel-vba nested vba excel

我有这个问题:

使用嵌套循环的任意组合创建Sub。这个嵌套循环应该输入女婴名字输入(下面)并打印出每个可能的组合。这些输入名称需要在某个工作簿中显示。打印出工作簿本身的组合。

输入
names

我已经能够让Penelope与所有中间名配对,但我无法弄清楚如何配对其余的名字。我不知道如何将活动单元格偏移到第二个名字,依此类推。这就是我到目前为止所做的:

Sub part2()
    Dim combination As String
    Dim fName As String
    Dim mName As String

    Range("A1").Activate
    fName = ActiveCell.Value

    Do Until IsEmpty(ActiveCell)
        mName = ActiveCell.Offset(0, 1).Value
        combination = fName & " " & mName
        ActiveCell.Offset(0, 3) = combination
        ActiveCell.Offset(1, 0).Activate
    Loop

1 个答案:

答案 0 :(得分:0)

你需要2个嵌套循环。第一个循环遍历列A(名字)和列A中的每一行循环到列B(中间名称)并组合它们:

std::shared_ptr<FILE> pipe(popen(dotnetCommand, "r"), pclose);

注意
这假设列A和B具有相同的行数。如果不是这种情况,则需要分别确定每列的最后一行:

Option Explicit

Public Sub CombineNames()
    Dim wsNames As Worksheet
    Set wsNames = Worksheets("Sheet1") 'define which worksheet to use

    Dim lRow As Long
    lRow = wsNames.Cells(wsNames.Cells.Rows.Count, "A").End(xlUp).Row 'find last used row

    Dim iRow As Long
    For iRow = 2 To lRow 'loop throug column A
        Dim jRow As Long
        For jRow = 2 To lRow 'for every row in column A loop through column B
            Debug.Print wsNames.Cells(iRow, "A").Value & " " & wsNames.Cells(jRow, "B").Value
              'change this line to your desired output
        Next jRow
    Next iRow
End Sub

并将循环调整为Dim lRowA As Long lRowA = wsNames.Cells(wsNames.Cells.Rows.Count, "A").End(xlUp).Row 'find last used row in column A Dim lRowB As Long lRowB = wsNames.Cells(wsNames.Cells.Rows.Count, "B").End(xlUp).Row 'find last used row in column B For iRow = 2 To lRowA