【发布时间】:2013-03-17 17:54:37
【问题描述】:
我有一个值y,我想知道该值是否在这组值中:x1, x2, ... xn。
我可以这样做:
if(y = x1 or y = x2 or .....)
但是有更好的方法吗?伪代码:
if(y in (x1, x2, ...., xn))
【问题讨论】:
标签: vba
我有一个值y,我想知道该值是否在这组值中:x1, x2, ... xn。
我可以这样做:
if(y = x1 or y = x2 or .....)
但是有更好的方法吗?伪代码:
if(y in (x1, x2, ...., xn))
【问题讨论】:
标签: vba
你可以写一个这样的辅助函数:
Public Function FindValue(ByVal ValueToFind As Variant, ParamArray SearchIn() As Variant)
Dim i As Integer
For i = 0 To UBound(SearchIn)
If SearchIn(i) = ValueToFind Then
FindValue = True
Exit Function
End If
Next
End Function
第二个参数(ParamArray)是一个数组,所以实际上可以传递不定数量的参数。
因此,您可以将所有值传递给此函数 - 首先要查找的值,然后是要搜索的所有值:
Dim Found As Boolean
Found = FindValue(y, x1, x2, x3, xn)
【讨论】:
您可以以与 (if then else) 相同的方式使用 Select Case:
Select Case Y
Case X1, X2, X3, ...
Do if True
Case Else
Do if False
End Select
【讨论】:
使用数组:
dim x(10)
x(1)=....
x(2)=....
y=....
for i=1 to 10
if x(i)=y then
....
end if
next i
【讨论】:
另一种方式
您可以访问 MS-Access 2000+ 吗? 如果是这样添加 Access Objects 库引用,您将能够使用 Eval 函数:
result = Eval("'y' IN ('x1', 'x2', '...' 'xn')")
它评估字符串表达式。可以使用一些 SQL 运算符,例如 IN。
见documentation
【讨论】:
dim values as string
values = "1,2,3,4,5," 'Note that comma is a separator and added towards the end as well.
dim lookupValue as string
lookupValue = ",4,"
dim found as Boolean
found = (instr(1, values, lookupValue) <> 0)
if found then
end if
编辑:另一种方式
dim lookupValue as long
lookupValue = 21000
dim values
set values = CreateObject("Scripting.Dictionary")
with values
.Add 1, 1
.Add 10, 1
.Add 100, 1
.Add 1000, 1
.Add 10000, 1
end with
dim found as Boolean
found = values.Exists(lookupValue)
【讨论】:
检查值是否存在很简单的方法是使用Match函数:
Dim myTBL As Variant
myTBL = Array(20, 30, 40, 50, 60)
'if value '30' exists in array than the position (which is >0) will be returned
Debug.Print WorksheetFunction.Match(30, myTBL, 0)
唯一的问题是,如果该值不存在,则 Match 函数会返回错误。因此,您应该使用错误处理技术。
对于不存在的值“70”,这可能看起来像:
'if doesn't exists error would be returned
On Error Resume Next
Debug.Print WorksheetFunction.Match(70, myTBL, 0)
If Err.Number <> 0 Then
Debug.Print "not exists"
Err.Clear
End If
很遗憾,这只适用于 Excel。
【讨论】:
选择一个在任何值中都不存在的分隔符(例如管道“|”),你可以在一行中完成:
If "|x1|x2|...|xn|" Like "*|" & y & "|*" Then
【讨论】:
"|"+x1+"|"+x2 等