簡體   English   中英

如果使用and,or運算符則比較復雜

[英]Complicated if with and, or operators

*我想創建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

但是,該代碼無法正常工作。 你有什么建議嗎?

問題是And的優先級高於or。 因此(強烈縮寫為可視化):

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)
  1. 信息應始終“不共享”

因此,您需要針對每種情況強制執行此操作,因此必須在上面加上其他括號:

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)

(如果未分割,則使用...)

根據您的描述,如果您的測試通過,則:

  • ele.Cells(m,2)=“未共享”

  • ele.Cells(m,3)或gc.Cells(m,3)=“正確”

因此您可以簡單地編寫以下代碼:

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()函數檢查子字符串“ | Correct |”的位置 在串聯詞中,即,如果兩個單元格中的任何一個內容精確地“正確”了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM