如果String包含某个子字符串

时间:2018-03-21 14:27:10

标签: vba excel-vba excel

在我的函数中,我试图检查某个字符串是否包含某个子字符串。对于非常短的字符串,它可以很好地工作,但是当我有一个带有空格的长字符串时,它似乎不再起作用了。

'Linear Fluorescent
T(1) = "1x4 1l"
T(2) = "1x4 1l basket"
T(3) = "1x4 2l"

'CFL
C(1) = "can- 1 4 pin"
C(2) = "can- 2 2 pin"
C(3) = "can- 2 4 pin"

For i = 1 To 3
If InStr(Fixture, T(i)) >= 1 Then

    ERP_Lamp = "Linear Fluorescent"

ElseIf InStr(Fixture, C(i)) >= 1 Then

    ERP_Lamp = "Compact Fluorescent"

End If
Next i

我得到的结果总是如此:" Linear Fluorescent"或0。 我似乎无法得到" Compact Fluorescent"即使夹具是" can-1 4 pin"它仍然会说线性荧光灯。

所以问题是:我如何检查我的字符串是否包含在我的其他字符串中#34; Fixture" ?

提前致谢。

1 个答案:

答案 0 :(得分:1)

不是答案,但在测试中重新调整了代码并添加了一些,但实质仍然是你的,并且工作正常。

Function ERP_Lamp(strFixture As String) As String

Dim t(3) As String
Dim c(3)   As String

t(1) = "1x4 1l"
t(2) = "1x4 1l basket"
t(3) = "1x4 2l"

'CFL
c(1) = "can- 1 4 pin"
c(2) = "can- 2 2 pin"
c(3) = "can- 2 4 pin"

strFixture = LCase(strFixture)

For i = 1 To 3

    If InStr(strFixture, LCase(t(i))) >= 1 Then

        ERP_Lamp = "Linear Fluorescent"
        Exit For

    ElseIf InStr(strFixture, LCase(c(i))) >= 1 Then

        ERP_Lamp = "Compact Fluorescent"
        Exit For

    End If

Next i

Erase t
Erase c

End Function