Boolean和If语句

时间:2017-09-05 11:13:42

标签: excel vba if-statement boolean

我有一个代码,可以将一个单元格数组转换为循环中的字符串。如果单元格包含特定字符串,它会正确地将trues放入布尔找到的变量中,但是跳过以这些变量为目标的if语句,并且只执行最后一个else语句。我不知道为什么会这样,并且会喜欢任何关于为什么if语句可能不会将变量视为true的输入。提前谢谢。

trimmedValX = Trim$(ur(r, m(6)))  *creates the string
      Found1 = InStr(trimmedValX, "still sold")      *checks to see if string is in the created string, if it is variable is set as True
      Found2 = InStr(trimmedValX, "Still sold")
      Found3 = InStr(trimmedValX, "Discontinued")
If Found3 = True Then
   cell1.Interior.Color = rColor
ElseIf Found1 = True or Found2 = True Then
   cell1.Interior.Color = gColor
Else
   cell1.Interior.Color = mColor
End If

2 个答案:

答案 0 :(得分:2)

InStr不会返回布尔值,而是返回子字符串的起始位置。请尝试使用它。 InStr Reference

trimmedValX = Trim$(ur(r, m(6)))  *creates the string
      Found1 = InStr(trimmedValX, "still sold")      *checks to see if string is in the created string, if it is variable is set as True
      Found2 = InStr(trimmedValX, "Still sold")
      Found3 = InStr(trimmedValX, "Discontinued")
If Found3 > 0 Then
   cell1.Interior.Color = rColor
ElseIf Found1 > 0 or Found2 > 0Then
   cell1.Interior.Color = gColor
Else
   cell1.Interior.Color = mColor
End If

答案 1 :(得分:0)

我会在InStr上提出一些建议

    trimmedValX = Trim$(ur(r, m(6)))

    With cell1.Interior
        If UCase(trimmedValX) Like "*DISCONTINUED*" Then
           .Color = rColor
        ElseIf UCase(trimmedValX) Like "*STILL SOLD*" Then
           .Color = gColor
        Else
           .Color = mColor
        End If
    End With