2017-02-14 101 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

沒問題,任何文字,所以它有點難.. –