嵌套For Loop打印输出不同范围

时间:2015-11-16 17:59:11

标签: vba excel-vba loops excel

代码应根据'Eth'中每个值的'Con'值显示五个不同的值。 “Con”和“Eth”中的值会更改数据透视表中的过滤器值。目前,代码将遍历所有7个“Eth”值,并将最终的值集(7)放在所有单元格中。这是以下代码的当前输出。Pivot Table manipulated by code

Code Output

我希望每个'选项'1-7的0-4值都是唯一的。

这是我目前的代码,

Sub Math()

Dim subject As String
Dim Shift As Variant
subject = "Math"
Sheets("Pivot").Range("B6") = subject
Sheets("Pivot").Range("G5") = subject

For Each Eth In Range("AL3:AL9")
For Five = 0 To 34 Step 5
            Set Shift = Range("B5").Offset(0, Five)
            Set Shft = Range("B7").Offset(0, Five)
    Dim x As Double
    Dim y As Double
Sheets("Pivot").Range("B4") = Eth
    For Each Con In Range("AM3:AM7")
        Sheets("Pivot").Range("B5") = Con
    x = Sheets("Pivot").Range("D2").Value
        Shift.Offset(0, Con).Value = x
    y = Sheets("Pivot").Range("D3").Value
        Shft.Offset(0, Con).Value = y

    Next Con

 Next Five
Next Eth

End Sub

1 个答案:

答案 0 :(得分:0)

你基本上有一个额外的循环,它在For Five = 0 to 34 Step 5中导致每次迭代都被写入所有单元格集。

试试这个:

Sub Math()

Dim subject As String, Shift As Range, Shft As Range

subject = "Math"

Sheets("Pivot").Range("B6") = subject
Sheets("Pivot").Range("G5") = subject

Dim Five As Long
Five = 0

For Each Eth In Range("AL3:AL9")

    Sheets("Pivot").Range("B4") = Eth
    Set Shift = Range("B5").Offset(0, Five)
    Set Shft = Range("B7").Offset(0, Five)

    Dim x As Double, y As Double

    For Each Con In Range("AM3:AM7")

        Sheets("Pivot").Range("B5") = Con
        x = Sheets("Pivot").Range("D2").Value
        Shift.Offset(0, Con).Value = x

        y = Sheets("Pivot").Range("D3").Value
        Shft.Offset(0, Con).Value = y

    Next Con

    Five = Five + 5

Next Eth

End Sub