vba循环FOR两张之间

时间:2017-09-09 09:19:32

标签: excel vba excel-vba

所以我有这个挑战。但首先给你一些信息:p从1到24。

当p为1且Cells(X,4)> 0时,我想存储所有值,当这是真的时(可能是多次,当它循环2000行时)到工作表中的值(“myvalues”)。细胞( 6 ,11).Value = a。

在此之后,我希望p为2,然后执行相同操作,并将这些总和存储到工作表(“myvalues”)。单元格( 7 ,11).Value = a。

依此类推,直到p为24(包括24)

Option Explicit
Sub main()

    Dim x As Integer
    Dim rowshift As Integer
    Dim a As Double
    Dim b As Integer, p as Integer

For x = 2 To 2000

If Worksheets("DATA").Cells(x, 2) = p And Worksheets("DATA").Cells(x, 4) > 0 Then
    a = a+ Worksheets("DATA").Cells(x, 5)

p=p+1

End If

For rowshift = 6 to 29

Worksheets("myvalues").Cells(rowshift, 11).Value = a

3 个答案:

答案 0 :(得分:1)

获得相当于Excel的公式

=SUMIFS(Data!$E$2:$E$2000,Data!$B$2:$B$2000,ROW()-5,Data!$D$‌​2:$D$2000,">0")

使用VBA,我建议您更改代码以在循环中进行循环

Option Explicit
Sub main()

    Dim x As Long
    Dim rowshift As Long
    Dim a As Double

    For rowshift = 6 to 29
        a = 0
        For x = 2 To 2000
            If Worksheets("DATA").Cells(x, 2) = rowshift - 5 And _
               Worksheets("DATA").Cells(x, 4) > 0 Then
                a = a + Worksheets("DATA").Cells(x, 5)
            End If
        Next
        Worksheets("myvalues").Cells(rowshift, 11).Value = a
    Next
End Sub

答案 1 :(得分:1)

这可能符合你的意图吗?

Sub Main()

    Dim TargetRow As Long
    Dim Spike As Double
    Dim p As Integer
    Dim R As Long

    TargetRow = 6
    For p = 1 To 24
        For R = 2 To 2000
            With Worksheets("DATA").Rows(R)
                If (.Cells(2).Value = p) And (.Cells(4).Value > 0) Then
                    Spike = Spike + .Cells(5).Value
                End If
            End With
        Next R
        Worksheets("MyValues").Cells(TargetRow, 11).Value = Spike
        Spike = 0
        TargetRow = TargetRow + 1
    Next p
End Sub

答案 2 :(得分:-1)

我认为你需要设置p值。 请试试这个完整的代码。

Option Explicit
Sub main()

    Dim x As Integer
    Dim rowshift As Integer
    Dim a As Double
    Dim b As Integer, p as Integer


    p = 1
    For x = 2 To 2000
        a = 0
        If p < 25 Then
           If Worksheets("DATA").Cells(x, 2) = p And Worksheets("DATA").Cells(x, 4) > 0 Then
               a = a+ Worksheets("DATA").Cells(x, 5)    
               p=p+1
           End If
        End If

        If a > 0 Then
            For rowshift = 6 to 29    
                Worksheets("myvalues").Cells(rowshift, 11).Value = a
            Next rowshift
        End If
   Next x