我尝试在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"
不等于&#34; L&#34;或&#34; R&#34;或者&#34; PD&#34;我希望我的回答是&#34;你的名单无效&#34;但我得到#VALUE!
我不清楚为什么会这样。
答案 0 :(得分:1)
您需要对代码进行一些修改:
为了让extent
拥有范围内的行数,请使用extent = list.rows.count
。
您不需要数组array_1()
,请看第3点。(感谢@ nightcrawler23注意)
您需要遍历list
(Range.Cells),并检查每个cell.Value
是否包含任何特殊字符(我在这里使用{{1}简化和缩短你的代码。)
代码(已测试)
Select Case
答案 1 :(得分:0)
或绕过循环并使用一行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