【问题标题】:Excel VBA If range.value = something thenExcel VBA 如果 range.value = something 然后
【发布时间】:2017-02-27 06:14:05
【问题描述】:

我要找的是这个 -

如果单元格范围内的值等于某个值或相同的值,那么它应该显示“正”,否则显示“负”。但是当我像下面的语法那样写时,它会抛出一个错误 -

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

Msgbox "Positive result"

else

Msgbox "Negative result"

end if

【问题讨论】:

  • “它抛出一个错误”是没有帮助的。 “它会引发类型不匹配错误”为我们提供了更多工作。

标签: excel if-statement range vba


【解决方案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

【讨论】:

    【解决方案2】:

    你需要这样的东西:

    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
    

    【讨论】:

    • 谢谢,但我有多个无法循环运行的范围。有没有办法可以直接验证它?没有任何循环
    • 我不这么认为。无论如何,这回答了问题。 For / Next 循环是完成这项工作的少量额外代码。
    【解决方案3】:

    你可以使用这个功能

        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
    

    【讨论】:

    • 注意:我没有添加任何错误/异常处理,因为解决方案仅用于说明。假设用户将为此目的进行必要的更改。
    • 这不是编写应用程序函数的正确语法。即Application.count。
    • 试试这个看看结果。我故意避免使用“Worksheetfunction”并使用“Application”来使用该功能。简而言之,像 Application.Count 这样的语句比 Worksheetfunction.Count 更稳定
    【解决方案4】:
    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。

    【讨论】:

    猜你喜欢
    • 2023-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    相关资源
    最近更新 更多