*我想创建if语句,如果符合条件,它会将值从一个表复制到另一个表。逻辑测试应如下: 1.信息应该始终是"不共享" 2.信息应该是"正确的"并且"纠正"或者"纠正"并且"错误"或"错误"并且"纠正" 下面你可能会看到我到目前为止的代码:
l = 2
For m = 2 To ElecRow
If ele.Cells(m, 2) = "Not Shared" And _
ele.Cells(m, 3) = "Correct" And gc.Cells(m, 3) = "Correct" _
Or ele.Cells(m, 3) = "Correct" And gc.Cells(m, 3) = "Reading is wrong" _
Or ele.Cells(m, 3) = "Reading is wrong" And gc.Cells(m, 3) = "Correct" Then
For i = k + 4 To f + 4
Selegas.Cells(l, 2).Value = ele.Cells(m, i).Value
Selegas.Cells(l, 4).Interior.Color = RGB(179, 182, 184)
l = l + 1
Next i
End If
Next m
但是,代码无效。你有什么建议吗?
答案 0 :(得分:2)
问题是并且优先级高于或。所以(可视化强烈缩写):
If e2 = ns And e3=c And gc=c Or e3=c And gc=r Or e3=r And gc=c
相当于
If (e2 = ns And e3=c And gc=c) Or (e3=c And gc=r) Or (e3=r And gc=c)
- 信息应始终为"不共享"
醇>
因此,您需要针对每种情况强制执行此操作,因此您必须使用其他括号来突破:
If e2 = ns And ((e3=c And gc=c) Or (e3=c And gc=r) Or (e3=r And gc=c))
与您的版本一样,再次省略多余的括号:
If e2 = ns And (e3=c And gc=c Or e3=c And gc=r Or e3=r And gc=c)
当你被困在优先点时,可能总是把括号放在第三个代码示例中。然后你再也不会错过任何东西......
你也可以通过拆分If:
来实现同样的目标If e2 = ns Then
If e3=c And gc=c Or e3=c And gc=r Or e3=r And gc=c Then
有机会优化和减少必要的比较次数:
If e2 = ns And (e3=c And (gc=c Or gc=r) Or e3=r And gc=c)
(使用未分割的if ...)
答案 1 :(得分:0)
根据您的描述,您的测试将在以下情况下通过:
ele.Cells(m,2)=“Not Shared”
和
ele.Cells(m,3)OR gc.Cells(m,3)=“Correct”
所以你可以简单地编码:
If ele.Cells(m, 2) = "Not Shared" And (ele.Cells(m, 3) = "Correct" Or gc.Cells(m, 3) = "Correct") Then
此外,将它们作为所有字符串,您可以使用以下替代方法:
Dim corrStrng As String
l = 2
For m = 2 To ElecRow
corrStrng = "|" & ele.Cells(m, 3) & "|" & gc.Cells(m, 3) & "|" '<--| concatenate two strings into one
If ele.Cells(m, 2) = "Not Shared" And InStr(corrStrng, "|Correct|") > 0 Then '<--| use Instr() to check if substring "|Correct|" is inside the concatenated word
使用Instr()
function检查子字符串是否为“|正确|”在连接的单词内,即如果两个父单元格中的任何一个内容精确地“正确”