You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA While循环多AND条件不生效 无法正确匹配工作表行如何解决?

问题根本原因

你编写的While循环的逻辑条件写反了,完全不符合预期的匹配规则。

你预期的循环逻辑是:只要当前行不是「操作员、设备、工序三个字段完全匹配」,就继续往下一行查找,但现有代码的判断逻辑是:

仅当当前行三个字段全部都不匹配输入值时,才继续循环,只要任意一个字段匹配,循环就会直接终止。

结合你给出的示例验证:你输入的操作员是Kevin,第一行A列值就是Kevin,此时Sheets("Summary").Cells(j, 1).Value <> operator的结果为False,AND连接的整个判断条件直接返回False,循环直接停在j=2,所以会错误覆盖第一行的已有数据。


修正方案

你可以选择任意一种修改方式,逻辑效果一致:

写法1:直接修改原有条件(改动最小)

把三个不等判断的连接符从And改成Or即可:

operator = UserForm_Finish.ComboBox1.Value
machine = UserForm_Finish.ComboBox2.Value
qty_prod = UserForm_Finish.TextBox1.Value
' 注意step是VBA保留关键字,建议修改为自定义变量名比如process_step
process_step = UserForm_Finish.ComboBox3.Value

t_finish = Now()

j = 2

While Sheets("Summary").Cells(j, 1).Value <> operator Or Sheets("Summary").Cells(j, 2).Value <> machine Or Sheets("Summary").Cells(j, 5).Value <> process_step
j = j + 1
    If j = 80 Then
       MsgBox ("There is an error")
        Exit Sub
    End If
Wend

t_start = Sheets("Summary").Cells(j, 10).Value
duration = t_finish - t_start
Sheets("Summary").Cells(j, 11).Value = t_finish
Sheets("Summary").Cells(j, 12).Value = duration
Sheets("Summary").Cells(j, 13).Value = qty_prod

写法2:逻辑更易读的写法(推荐)

直接判断三个条件是否完全匹配,不匹配就继续循环,不用绕反逻辑:

While Not (Sheets("Summary").Cells(j, 1).Value = operator And Sheets("Summary").Cells(j, 2).Value = machine And Sheets("Summary").Cells(j, 5).Value = process_step)
j = j + 1
    If j = 80 Then
       MsgBox ("There is an error")
        Exit Sub
    End If
Wend

附加注意点

你原代码里的变量名step是VBA的内置保留关键字(用于For循环的步长参数),建议修改为process_step或step_name这类自定义名称,避免后续出现难以排查的语法冲突。

内容的提问来源于stack exchange,提问作者AHMAD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 11:30:00