Vbscript QTP:检查字符串数组是否包含值

Vbscript QTP:检查字符串数组是否包含值,vbscript,automated-tests,qtp,Vbscript,Automated Tests,Qtp,我很难让我的测试用例正确运行 问题在下面的代码中,第一个if语句是精确的。QTP抱怨需要一个对象 For j=Lbound(options) to Ubound(options) If options(j).Contains(choice) Then MsgBox("Found " & FindThisString & " at index " & _ options.IndexOf(choice)) Else

我很难让我的测试用例正确运行

问题在下面的代码中,第一个if语句是精确的。QTP抱怨需要一个对象

For j=Lbound(options) to Ubound(options)
    If options(j).Contains(choice) Then
        MsgBox("Found " & FindThisString & " at index " & _
        options.IndexOf(choice))
    Else
        MsgBox "String not found!"
    End If
Next
当我检查数组时,我可以看到它已正确填充,“j”也是正确的字符串。
非常感谢您对此问题提供的任何帮助。

VBScript中的字符串不是对象,因为它们没有成员函数。应使用函数来搜索子字符串

For j=Lbound(options) to Ubound(options)
    If InStr(options(j), choice) <> 0 Then
        MsgBox("Found " & choice & " at index " & j
    Else
        MsgBox "String not found!"
    End If
Next
j=Lbound(选项)到Ubound(选项)的

如果InStr(选项(j),选项)为0,则
MsgBox(“找到的”&choice&“在索引处”&j
其他的
MsgBox“未找到字符串!”
如果结束
下一个

您好,如果您检查数组中的精确字符串而不是子字符串,请使用StrComb,因为如果使用InStr,则如果array=“apple1”、“apple2”、“apple3”、“apple”和choice=“apple”,则所有数组项都将返回pass

Function CompareStrings ( arrayItems , choice )

For i=Lbound(arrayItems) to Ubound(arrayItems)

    ' 1 - for binary comparison "Case sensitive
    ' 0 - not case sensitive
    If StrComp(arrayItems(i), choice , 1) = 0 Then

    CompareStrings = True
    MsgBox("Found " & choice & " at index " & i

    Else

    CompareStrings = False
    MsgBox "String not found!"

    End If

Next

End Function

检查字符串数组是否包含值的简明方法是组合and函数:

If Ubound(Filter(options, choice)) > -1 Then
    MsgBox "Found"
Else
    MsgBox "Not found!"
End If
缺点:找不到元素所在的索引


优点:它很简单,您可以使用通常的include和compare参数来指定匹配条件。

@gbonetti-您的代码返回“find”作为下面的示例。我认为这是因为@Giacomo Lacava提到的原因

    a = Array("18")

    If Ubound(Filter(a, "1")) > -1 Then
       MsgBox "Found"
    Else
       MsgBox "Not found!"
    End If

options
的内容是什么?这些字符串是某种类型的测试对象(如果是什么类型的)?我正在填充这样的选项:
options(0)=“welcome”
,如果我是正确的,这是字符串。它是一个固定大小的数组。啊,是的。这解释了我遇到的问题。谢谢你提供的信息性答案。而不是(错误!)神奇的数字,应该使用常量vbTextCompare/vbBinaryCompare();在循环中设置返回值没有意义。抱歉..你对循环的看法是正确的…但我已经尝试传递0和1,它似乎工作正常..我认为代替vbTextCompare/vbBinaryCompare 0和1工作正常..谢谢“工作(正常)”不是软件质量的有效标准。不必抱歉,但请更正您的贡献。请检查:,,也感谢您的观点“工作(良好)”对软件质量不合适..根据我的参考资料,使用0和1可以工作..谢谢你现在你的函数不是函数,你仍然不使用常量。请删除此“答案”并更正你以前的答案(包含指向StrComp()的有价值的指针)。如果我正确理解文档,此解决方案的问题是筛选器将返回选择为子字符串的所有元素。例如,对于包含“Dune”、“Dunebug”、“Blah”和choice=“Dune”的数组,它将返回两项。
    a = Array("18")

    If Ubound(Filter(a, "1")) > -1 Then
       MsgBox "Found"
    Else
       MsgBox "Not found!"
    End If