如何检查数组中的值是否为真

时间:2016-04-26 09:59:41

标签: vba word-vba

我正在使用vba,我得到str作为字符串 我想完成以下任务。

有以下数组;

array1 = (string1, string2, string4)
array2 = (string3, string6, string7)
array3 = (string3, string6, string7)

str = some string

if str is present in array2 then
 sbj = "subject2"

if str is present in array1 then
sbj = subject1
明智的 我知道我很困惑,但目前我仍然坚持使用长开关功能(效果很好)

Function sw(s)
    sw = Switch(s = "a", "Apple", s = "b", "Banana", s = "c", "Apple", s="d", "banana")
End Function

表示a和c都是苹果,b和d都是香蕉。我们可以为此使用其他东西吗?

2 个答案:

答案 0 :(得分:2)

加入数组并检查

Dim test As Boolean
Dim findStr As String
Dim result As String

findStr = "apple"

varArray = Array("banana", "apple", "pear", "orange")

test = Join$(varArray, " ") Like "*apple*"

result = "apple is " & IIf(test, vbNullString, "not ") & "included"

节省了必须遍历数组。

更好的是重新思考你的方法。数组是以非常基本的方式存储类似数据的集合,但是您需要更有用的东西,所以请改为使用CollectionDictionaryArrayList对象。

答案 1 :(得分:1)

您可以定义一个私有函数来检查元素是否在数组中,并在IF .. THEN子句中使用此函数。

Public Function elemInArray(ByVal elem As Variant, ByVal Arr As Variant) As Boolean

    Dim el As Variant

    elemInArray = False

    Select Case IsObject(elem)
    Case True
        For Each el In Arr
            If el Is elem Then elemInArray = True: Exit Function
        Next el

    Case False
        For Each el In Arr
            If el = elem Then elemInArray = True: Exit Function
        Next el

    End Select

End Function

编辑:或者这个更简单的函数,如果你的数组只包含基本类型

Public Function elemInArray(ByVal elem As Variant, ByVal Arr As Variant) As Boolean

    Dim el As Variant

    elemInArray = False

    For Each el In Arr
        If el = elem Then elemInArray = True: Exit Function
    Next el

End Function

然后你可以问这样的事情:

if elemInArray(str, arr1) then 
    sbj = "subject1"

至于你的第二个问题,你也可以使用IF条件或SELECT CASE语句,如下所示:

IF s = "a" or s = "c" then
    sw = "Apple"
ELSEIF s = "b" or s = "d" then
    sw = "banana"
ELSE
    err.raise 10000,"Unexpected value"
ENDIF

SELECT CASE sw
CASE "a","c"
    sw = "Apple"
CASE "b","d"
    sw = "Banana"
CASE else
    err.raise 10000,"Unexpected value"
END SELECT

如果你可以保证s将是" a"," b"," c"之一,你可以省略ELSE部分。或" d"。

此致