【问题标题】:Exit Function When Conditions Are Not Met - Visual Basic不满足条件时的退出函数 - Visual Basic
【发布时间】:2017-05-07 17:32:17
【问题描述】:

我正在尝试在 Visual Basic 中编写一个函数,如果满足某些条件,它将运行该函数。如果不是,则函数将终止。

现在我有以下,

Function answer(list As range) As String

    Dim extent As Integer
    extent = list.rows.Value
    Dim array_1() As Double
    ReDim array_1(1 To extent) As Double
    Dim i As Integer

    For i = 1 To extent
        array_1(i) = list(i).value
        If array_1(i) <> "L" Or array_1(i) <> "R" Or array_1(i) <> "PD" Or array_1(i) <> "D" Or array_1(i) <> "PD" Or array_1(i) <> "P" Or array_1(i) <> "S" Then
            answer = "Your list is not valid"
            Exit Function
        End If
        Next i

    'Otherwise function will perform rest of code

    answer = "Your list is valid"

End Function

如果我的输入是:例如=answer(A1:A6)...假设A1 = "XXX" 不等于“L”或“R”或“PD”等。我希望我的回答是“您的列表是无效”,但我得到了#VALUE!

我不清楚为什么会这样。

【问题讨论】:

  • extent = list.rows.count
  • @Soto 您在下面的答案中尝试过我的代码吗?有什么反馈吗?
  • @ShaiRado 我有。奇迹般有效!谢谢老哥

标签: arrays excel vba function


【解决方案1】:

您需要对代码进行一些修改:

  1. 为了使extent 具有范围内的行数,请使用extent = list.rows.count

  2. 您不需要数组 array_1() ,请查看第 3 点。(感谢 @nightcrawler23 的注意)

  3. 1234563你的代码)。

代码(已测试)

Function answer(list As Range) As String

    Dim extent As Long
    Dim cell As Range

    extent = list.Rows.Count

    ReDim array_1(1 To extent)

    For Each cell In list.Cells
        Select Case cell.Value
            Case "L", "R", "PD", "D", "S"

            Case Else
                answer = "Your list is not valid"
                Exit Function

        End Select
    Next cell

    'Otherwise function will perform rest of code
    answer = "Your list is valid"

End Function

【讨论】:

  • 您根本不需要array_1。这会减少很多代码。
  • 只要使用Select Case cell.Value
  • @nightcrawler23 谢谢,你是对的,我使用的是原始代码,我没有注意到它不需要。
【解决方案2】:

或绕过循环并使用一行COUNTIF

测试

Sub GetValues()
MsgBox Answer([A1:B10])
End Sub

功能

Function Answer(list As Range) As Boolean
Answer = (Evaluate("Sum(COUNTIF(" & list.Address & ",{""L"",""R"",""PD"",""D"",""S""}))") = list.Cells.Count)
End Function

【讨论】:

    猜你喜欢
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多