Excel VBA如果range.value = something,那么

时间:2016-10-18 05:37:55

标签: excel-vba if-statement range vba excel

我正在寻找的是这个 -

如果单元格范围内的值等于某个值或相同值,则应显示"正数"否则"否定。但是当我写下面的语法时,它会抛出一个错误 -

If range("F3:H5").value = "X" then

Msgbox "Positive result"

else

Msgbox "Negative result"

end if

4 个答案:

答案 0 :(得分:1)

它应该达到目的:

Sub string_validation()

    Dim cel As Range

    For Each cel In Range("F3:H8")
        If cel.Value = "hassle" Then
            MsgBox "Positive result"
        Else
            MsgBox "Negative result"
        End If
    Next cel

End Sub

答案 1 :(得分:0)

你需要这样的东西:

Dim found As Boolean
found = False
For Each cell In Range("F3:h5").Cells
    if cell.Value = "X" Then
        found = True
    end if
Next

If found = True Then
    Msgbox "Positive result"
else
    Msgbox "Negative result"
End if

答案 2 :(得分:0)

您可以使用此功能

    Function EvalRange(inRng As Range, inVal As Variant) As Variant

    Dim CntAll, CntMatch As Double

    CntAll = Application.Count(inRng)
    CntMatch = Application.CountIf(inRng, inVal)

    If CntAll = CntMatch Then
        EvalRange = "Positive Result"
        Else: EvalRange = "Negative Result"
    End If

    End Function

答案 3 :(得分:0)

VBA.MsgBox VBA.IIf(Evaluate("=SUMPRODUCT(--(F3:H5 = ""X""))"), "Positive result", "Negative result")

“”X“”由于两个外部引号引用的双引号

F3:H5 =“”X“”是一个布尔结果数组F3 = X,F4 = X等。

- 负将布尔值变为0/1;另一个消极的“回”到1/0

IIf,Evaluate,SUMPRODUCT ...功能。对不起,GIYF。