2017-02-14 99 views
1

我的问题是如何检查一个字符串在开始时是否有“文本”&“_”。切特殊字符串-VBA

例如:

If sText = test.docx Then Function = False 
ElseIF sText = Test_test.docx Then Function = True 
End If 

我怎么之前_不测试,如果有几个_字符串中它也可以

+1

你可能会喜欢看斯普利特 – Fionnuala

+0

您可以用' Instr'。试试这个例子:如果InStr(1,“Test_abcde”,“test”&“_”,vbTextCompare)= 1那么' –

+0

你也可以使用'Like'运算符:'如果sText Like“Test_ *”那么' – ThunderFrame

回答

0

使用INSTR()开始如下所示:

foo="test"&"_" 
bar="test_test.docx" 
if Instr(bar, foo)>0 then function = true 
else function = false 
end if 

Instr(bar,foo)在字符串栏中显示子字符串foo的位置。 如果没有这样子的话,就返回零 如果您需要检查的任何文字,这不是一个问题,用这个条件:

foo="_" 
n=4 
bar"test_textt.docx" 
m=Instr(bar,foo) 
if (m>n)and(len(bar)>m) then function=true 
else function=false 
end if 

这里N - 字符数,这将是之前“ “ 如果你不知道有多少个字符可能会有,只是n设置为0或1 如果”“migth是最后一个字符,然后删除条件(len(bar)>m)

+0

先生,感谢您的回答,但这应该是可能的任何文字 –

+0

我编辑答案,检查它) –

+0

非常感谢!工作正常! –

-1

你可以简单地正确地切断该字符串,则文本也时检查字符串TEST_

dim res as boolean, filename as string 
res = false 
filename = "" 
' if the len is not Superior to 5 (len of test_), don't check 
if len(sText) > 5 then 
    ' if the left part begin with test_ 
    if left(lcase(sText), 5) = "test_" then 
    res = true 
    ' if you want to retrieve the filename without test 
    filename = mid(sText, 6) 
    end if 
end if 
+0

谢谢对于你的答案,但开始也可能是ABC_或AD_,所以解决方案必须是其他 –

+0

对不起,我误读了,我以为你想检查“Test_”而不是“任何文本”。你想检查任何文字?或可能的文字是预设的? –

+0

没问题,任何文字,所以它有点难.. –