简体   繁体   English

循环检查总和,取决于具有未知条目的几列

[英]Loop to check sums, depending on several columns with unknown entries

I am dealing with data validation in Excel VBA.我正在处理 Excel VBA 中的数据验证。

I receive lists of employees, dates and quantities, and before further processing I need to check if ANY employee (column A) at ANY date (column B) had more than a certain total quantity of something (column C; conditional sum).我收到员工、日期和数量的列表,在进一步处理之前,我需要检查任何日期(B 列)的任何员工(A 列)是否拥有超过某个特定总量(C 列;条件总和)。

As an example, let's assume I want to check incoming sheets of the following format:例如,假设我想检查以下格式的传入工作表:

例子

… and I need to raise a warning, if any employee had more than one full cookie on any day. ......如果任何员工在任何一天吃过一个以上的完整饼干,我需要发出警告。 (In the example, it should raise a warning, because Ben had 1.2 cookies on Jan 1ˢᵗ.) (在示例中,它应该发出警告,因为 Ben 在 1 月 1ˢᵗ 有 1.2 个 cookie。)

Assumptions:假设:

  • I do not know which names are on the list.我不知道名单上有哪些名字。
  • I do not know how many entries per day this person had.我不知道这个人每天有多少条目。
  • I do not know the order of the entries in the incoming sheets.我不知道传入工作表中条目的顺序。

My current approach would be to filter columns A and B for unique values, loop over these two lists and apply a SumIfS to sum the respective values in column C. This seems totally inefficient however, as it involves many nested loops, and it is rather the "Excel"-way than the "VBA" way.我目前的方法是过滤 A 列和 B 列的唯一值,遍历这两个列表并应用 SumIfS 对 C 列中的相应值求和。 然而,这似乎完全低效,因为它涉及许多嵌套循环,而且它是“Excel”方式比“VBA”方式。

How can I solve this problem using VBA properly?如何正确使用 VBA 解决此问题?

Just use the SUMIFS function to get the total amount of cookies each employee had a single day:只需使用SUMIFS 函数即可获取每个员工一天拥有的 cookie 总量:

=SUMIFS(C:C,A:A,A:A,B:B,B:B) 'alternatively =SUMIFS(C:C,A:A,A2,B:B,B2)

=IF(SUMIFS(C:C,A:A,A:A,B:B,B:B) > 1,A:A & " is too fat", A:A & " can eat more")

For german Excel use:对于德语 Excel 使用:

=SUMMEWENNS(C:C;A:A;A:A;B:B;B:B) 'alternatively =SUMMEWENNS(C:C;A:A;A2;B:B;B2)

=WENN(SUMMEWENNS(C:C;A:A;A:A;B:B;B:B) > 1;A:A & " is too fat"; A:A & " can eat more")

在此处输入图片说明

If you need a VBA solution have a look at the WorksheetFunction.SumIfs method or just write that formula with VBA into the column:如果您需要 VBA 解决方案,请查看WorksheetFunction.SumIfs 方法,或者只需将带有 VBA 的公式写入列中:

Range("E2:E20").Formula = "=SUMIFS(C:C,A:A,A:A,B:B,B:B)" '<-- takes only english formula

eg.例如。 to use it for easy filtering later (eg. to get a list of all fat employees).稍后使用它来轻松过滤(例如,获取所有胖员工的列表)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM