条件未满足时退出函数 – Visual Basic

我试图编写一个函数在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 

如果我的input是: =answer(A1:A6)例如…可以说, A1 = "XXX"不等于“L”或“R”或“PD”等我希望我的答案是“你的名单是无效的“,而是我得到#VALUE!

我不清楚为什么是这样。

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

  1. 为了extent的行数,使用extent = list.rows.count

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

  3. 你需要遍历你的list (Range.Cells),并检查每个cell.Value是否不包含任何特殊字符(我在这里使用Select Case来简化和缩短代码)。

代码 (testing)

 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 

或绕过循环并使用一行COUNTIF

testing

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

function

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