VBA 嵌套 if-do-while 来求和值

问题描述 投票:0回答:1

我正在尝试做什么:

循环浏览 2 个工作表(同一工作簿),比较 2 个标准(农场和批次)。如果条件匹配,则将“编号”中的值相加。样本”单元格并粘贴到“样本总数”

实际发生了什么:

满足两个条件时,前 2 行值将被求和并粘贴到正确的单元格中。但只有前 2 行。所以 Do While 并不是...doing while。否则它有理由跳过单元格或提前退出循环。我怀疑我正在进行太多迭代。正如我发现的那样,Do 循环很容易演变成无限循环。

此外,我的即时窗口显示第 1815 行中的第一次迭代,而不是第 3 行。(s = 源页面中的行号)

New Sum: 190

s, Num Samples: 1815, 95 

我不确定从这里到底该去哪里,任何见解将不胜感激。

Sub ProjectDataCalcs()

Dim Src As Worksheet: Set Src = Sheets("Plate Analysis")
Dim Dest As Worksheet: Set Dest = Sheets("Project Analysis")

Dim Sum As Long
Sum = 0
Dim s As Long, d As Long, LR As long, LR2 As Long

LR = Dest.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LR2 = Src.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    ' effectively a SUMIFS loop
        For s = 3 To LR2
        Sum = Src.Cells(s, "D").Value ' Number of Samples per Plate
        Debug.Print "s, Num Samples: " & s & ", " & (Sum)
         For d = 3 To LR
        'while batch = batch and farm = farm,
        'sum cell value (not add row count) number of samples per plate
         Do While Src.Cells(s, "H").Value = Dest.Cells(d, "E").Value And _
         Src.Cells(s, "I").Value = Dest.Cells(d, "D")

            'Add value in cell to existing value;
            'add Number of Samples in line to running total of samples
            Sum = Sum + Src.Cells(s, "D").Value

            Debug.Print "New Sum: " & (Sum)
            'Sum to Total Samples cell in col L
            Dest.Cells(d, "L").Value = Sum
            Exit Do
          Loop
         Next d
        Next s

End Sub
excel vba nested-loops do-while sumifs
1个回答
0
投票

我认为除了基本的嵌套循环之外你不需要任何其他东西:

Sub ProjectDataCalcs()

    Dim Src As Worksheet, Dest As Worksheet
    Dim Sum As Long, batch, farm
    Dim s As Long, d As Long, LR As Long, LR2 As Long

    Set Src = Sheets("Plate Analysis")
    Set Dest = Sheets("Project Analysis")
    
    LR = Dest.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    LR2 = Src.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
            
    ' effectively a SUMIFS loop
    For s = 3 To LR2
        batch = Src.Cells(s, "H").Value 'populate these outside the inner loop...
        farm = Src.Cells(s, "I").Value
        Sum = Src.Cells(s, "D").Value   '#Samples per Plate
        Debug.Print s, "Batch", batch, "Farm", farm, "#Samples", Sum
        
        For d = 3 To LR
            'if batch = batch and farm = farm, add #samples per plate
            If batch = Dest.Cells(d, "E").Value And farm = Dest.Cells(d, "D") Then
                Sum = Sum + Src.Cells(s, "D").Value
                Debug.Print , d, "New Sum: " & (Sum)
                Exit For '## if only expecting a single row to match
            End If
        Next d
        Dest.Cells(d, "L").Value = Sum 'only need this once...
    Next s
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.