2012-08-09 153 views
5

我无法正确运行测试用例。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 
     MsgBox "String not found!" 
    End If 
Next 

当我检查数组我可以看到它正确填充和“J”也是正确的字符串。 任何有关这个问题的帮助将不胜感激。

+0

'options'的内容是什么?是这些字符串,某种测试对象(如果是的话)? – Motti 2012-08-09 09:52:36

+0

我正在填充如下所示的选项: 'options(0)=“welcome”'这是字符串,如果我是正确的。 它是一个固定大小的阵列。 – L337BEAN 2012-08-09 09:58:46

回答

13

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

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 
+0

啊是的。这解释了我遇到的问题。感谢您提供丰富的答案。 – L337BEAN 2012-08-09 12:15:50

-2

你好,如果你在阵列中使用StrComb检查精确的字符串没有子字符串,因为如果使用InStr函数那么如果数组=“apple1”,“apple2”,“apple3”,“苹果”和选择=“苹果“然后所有人都会为每个阵列项目返回通过。

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 
+0

应该使用常量vbTextCompare/vbBinaryCompare(http://msdn.microsoft.com/en-us/library/05z4sfc7%28v=vs.84%29.aspx);而不是(错误!)幻数。在循环中设置返回值*是没有意义的。 – 2014-01-21 13:31:46

+0

对不起..你是对的...还有特殊的循环...谢谢 – 2014-01-21 13:55:00

+0

对不起..你是对的循环...但我已经尝试传递0和1它似乎工作正常..我认为,而不是vbTextCompare/vbBinaryCompare 0和1工作正常..谢谢 – 2014-01-21 14:07:09

0
Function CompareStrings (arrayItems , choice) 
For i=Lbound(arrayItems) to Ubound(arrayItems) 

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

MsgBox("Found " & choice & " at index " & i 

Else 

MsgBox "String not found!" 

End If 

Next 

End Function 
+0

现在你的函数不是函数,你仍然不使用常量。请删除此“答案”并更正以前的答案(包含指向StrComp()的有价值指针)。 – 2014-01-21 14:09:59

10

一个简洁的方式来检查字符串数组包含一个值是将FilterUBound功能组合:

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

缺点:你没有得到的指标,其中元素被发现

优点:它很简单,你有通常的包含和比较参数来指定匹配标准。

+1

如果我正确理解文档,这个解决方案的问题是Filter将返回所有选择是子字符串的元素。例如。使用包含“Dune”,“Dunebug”,“Blah”和choice =“Dune”的数组时,它将返回两个项目。 – 2016-04-06 13:26:59

相关问题