我有一个值y
,我想知道该值是否在这组值中:x1, x2, ... xn
。VBA查找值是否在值
我能做到这一点是这样的:
if(y = x1 or y = x2 or .....)
但是,有没有更好的办法?伪代码:
if(y in (x1, x2, ...., xn))
我有一个值y
,我想知道该值是否在这组值中:x1, x2, ... xn
。VBA查找值是否在值
我能做到这一点是这样的:
if(y = x1 or y = x2 or .....)
但是,有没有更好的办法?伪代码:
if(y in (x1, x2, ...., xn))
你可以写一个辅助函数,像这样的:
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)
使用数组:
dim x(10)
x(1)=....
x(2)=....
y=....
for i=1 to 10
if x(i)=y then
....
end if
next i
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中才起作用。
另一种方式
你有权访问MS-Access 2000+吗? 如果是添加访问对象库引用,你将能够使用eval函数:
result = Eval("'y' IN ('x1', 'x2', '...' 'xn')")
它评估字符串表达式。可以使用一些SQL运算符,如IN
。 见documentation
您可以用相同的方式使用选择案例(如果当时人):
Select Case Y
Case X1, X2, X3, ...
Do if True
Case Else
Do if False
End Select