【问题标题】:UDF for If statement with multiple components具有多个组件的 If 语句的 UDF
【发布时间】:2015-12-18 15:26:00
【问题描述】:

我正在尝试创建一个函数 (=StatusExpected),该函数将在评估多个组件后返回通过/失败。具体来说,四个组件(规模、流动性、资格、例外)返回“通过/失败”。如果所有四个都返回“通过”,我想要 StatusExpected="Pass"。如果这些组件中的一个或多个返回“失败”,我希望 StatusExpected="Fail"。

StatusExpected 填充 I7:I506,并且四个变量填充每一行,分别在 J、AB、AF、AP 中直接交叉。但是,我认为这无关紧要,因为我正在寻找具有四个输入的功能。

以下是我所拥有但不起作用的内容:

Function StatusExpected(Size As String, Liquidity As String, Qualified As String, Exception As String)
    Range("A1").Select.Activate
    If Size = "Pass" And Liquidity = "Pass" And Qualified = "Pass" And Exception = "Pass" Then
        StatusExpected = "Pass"
    Else
        StatusExpected = "Fail"
    End If
End Function

如果可以,还请回复您是否需要激活单元格,或者是否需要定义变量。请从 Function 行从头开始编写代码,就好像什么都不存在一样,并为我提供除了我的问题之外的任何可以帮助我的东西,以及为清晰起见的最佳实践。

【问题讨论】:

  • 我不相信 .Select.Activate 是有效的语法,ActivateSelect 几乎从不需要。大多数操作可以在没有代码的情况下完成(这会降低性能)。
  • 函数状态预期(大小为字符串,流动性为字符串,合格为字符串,异常为字符串)如果大小 =“通过”且流动性 =“通过”且合格 =“通过”且异常 =“通过” " Then StatusExpected = "Pass" Else StatusExpected = "Fail" End If End Function 仍然不适合我 仍然不适合我,你知道为什么会失败吗?抢先“通过”和“失败”总是使用相同的大小写 Else StatusExpected = "Fail" End If End Function
  • 当我在“I”中输入 =StatusExpected 时,它会突出显示低至 506 的整个单元格范围
  • 你在 J7 单元格中使用了什么公式?

标签: vba function excel if-statement


【解决方案1】:

开始:

.Select.Activate

语法无效。它应该是其中之一。然而,在大多数情况下,这是一个不必要的操作,会影响性能(通常对于小型操作来说并不明显,但为了良好的编码习惯,您应该避免使用 .Select.Activate

所以你的功能:

Function StatusExpected(Size As String, Liquidity As String, Qualified As String, Exception As String)
    If Size = "Pass" And Liquidity = "Pass" And Qualified = "Pass" And Exception = "Pass" Then
        StatusExpected = "Pass"
    Else
        StatusExpected = "Fail"
    End If
End Function

为我工作(Excel 2013)。

我注意到的一件事是这个函数区分大小写。考虑 J、AB、AF、AP 列中的以下数据:

+------+------+------+------+
| Pass | Pass | Pass | Pass |
+------+------+------+------+
| PASS | PASS | PASS | PASS |
+------+------+------+------+

您的函数会为第一行返回Pass,但会为第二行返回Fail,因为默认情况下,文本比较区分大小写。

改变这种情况的一种方法是将Option Compare Text 行添加到代码的顶部,这将使文本比较不区分大小写。所以如果你这样做:

Option Compare Text

Function StatusExpected(Size As String, Liquidity As String, Qualified As String, Exception As String)
    If Size = "Pass" And Liquidity = "Pass" And Qualified = "Pass" And Exception = "Pass" Then
        StatusExpected = "Pass"
    Else
        StatusExpected = "Fail"
    End If
End Function

上面的数据集在这两种情况下都会返回Pass

【讨论】:

  • 感谢您的案例提示。我使用的是 2010,该功能对我不起作用。有什么理由想到为什么会这样?
  • @IanK 尝试验证是否实际调用了该函数:在其中的一行代码上放置一个断点,然后刷新工作表中的一个单元格。被调用了吗?
  • 太棒了!那你会分享你的解决方案吗? :)
  • 上面是Soulfire提供的解决方案
猜你喜欢
  • 2014-10-20
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2016-12-13
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多