【问题标题】:How can i use For Loop correctly for multiple conditions如何正确使用 For Loop 处理多个条件
【发布时间】:2017-04-29 22:31:57
【问题描述】:

我在下面有以下循环:

With Sheets("Sheet Name")
    For i = 2 To 26
        .Cells(11, i).Formula = Application.WorksheetFunction.CountIfs(Sheets("Sheet1").Range("F8:F" & n), Sheets("Sheet2").Range(Chr(64 + i) & "8"), Sheets("Sheet1").Range("AC8:AC" & n), "S")
        .Cells(12, i).Formula = Application.WorksheetFunction.CountIfs(Sheets("Sheet1").Range("F8:F" & n), Sheets("Sheet2").Range(Chr(64 + i) & "8"), Sheets("Sheet1").Range("AC8:AC" & n), "YS")            
    Next i
End With

每行末尾的最后一个条件由一个字符串更改,即“S”、“YS”。我想避免必须为每个“S”和“YS”使用 1 行等等,即每个标准会有很多行。然后我还想添加另一个处理行的 for 循环

【问题讨论】:

  • 你说的是什么意思...需要想办法把它放到一行中...
  • 抱歉不够清晰,将在@FDavidov上方更新

标签: excel vba loops for-loop


【解决方案1】:

我长长的问题和改进列表中的下一步是模拟这一点,但对于 SUMIFS,因为我正在查看成本数据。

请看下面,我希望其他人可以从中受益,也许会有所改进!

With Sheets("Operations Schedules -Summary")
    For i = 2 To 26
        For j = 0 To UBound(codes)
            .Cells(37 + j, i).Formula = Application.WorksheetFunction.SumIfs(Sheets("Sheet1").Range("AD8:AD" & n), Sheets("Sheet1").Range("F8:F" & n), Sheets("Sheet2").Range(Chr(64 + i) & "8"), Sheets("Sheet1").Range("AC8:AC" & n), codes(j))
        Next j
    Next i
End With

SUMIFS 的一些基本语法:

  • 第一部分是指定求和范围
  • 第二部分是指定条件范围,然后是条件
  • 我相信这适用于 197 条标准!

对于查看上述变量的各种限定条件的任何新手:

  • i、j 和 n 是 long 类型的变量。 n 用于(动态)计算目标数据集中的行数

【讨论】:

    【解决方案2】:
    codes = Array("S", "YS")
    For i = 2 To 26
        For j = 0 to UBound(codes)
            Sheets("Sheet Name").Cells(11+j, i).Formula = Application.WorksheetFunction.CountIfs(Sheets("Sheet1").Range("F8:F" & n), Sheets("Sheet2").Range(Chr(64 + i) & "8"), Sheets("Sheet1").Range("AC8:AC" & n), codes(j))
        Next j
    Next i
    

    【讨论】:

    • 完美运行!我知道一定有办法,需要更多地研究数组!
    猜你喜欢
    • 1970-01-01
    • 2017-02-11
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2012-03-26
    • 2021-10-23
    • 2012-06-23
    相关资源
    最近更新 更多