2016-08-31 49 views
3

我有一個腳本讀取以逗號分隔的文本文件,但是無論何時使用Trim(str)我已經在文件中提取的其中一個值上,它將不起作用...Vbscript修剪功能

我的文本文件:

some string, anotherstring, onelaststring 
some string, anotherstring, onelaststring 
some string, anotherstring, onelaststring 
some string, anotherstring, onelaststring 

我的腳本:

Dim fso, myTxtFile 
Set fso = CreateObject("Scripting.FileSystemObject") 
Set myTxtFile = fso.OpenTextFile("mytxt.txt") 

Dim str, myTxtArr 
txtContents myTxtFile.ReadAll 
myTxtFile.close 
myTxtArr = Split(txtContents, vbNewLine) 

For each line in myTxtArr 
    tLine = Split(tLine, ",") 
    Trim(tLine(1)) 
    If tLine(1) = "anotherstring" Then 
     MsgBox "match" 
    End If 
Next 

我的劇本從來沒有達到 「匹配」,我不知道爲什麼。

+0

你是否得到一個數組越界的錯誤? – STLDeveloper

+0

沒有錯誤,只是沒有修剪 – tarki

+1

'trim(「一些字符串,anothertring,onelaststring」)'不等於''anothertring「''。也許你想分割「,」的線? –

回答

3

Trim()是一個函數,返回修剪後的字符串。你的代碼使用不當。您需要使用返回值:

myTxtArr(1) = Trim(myTxtArr(1)) 

或使用其他變量來存儲的價值,並使用獨立的變量比較,

trimmedStr = Trim(myTxtArr(1)) 
If trimmedStr = "anotherstring" Then 

,或者你可以直接使用函數返回值在比較中,

If Trim(myTxtArr(1)) = "anotherstring" Then 

這裏是你的代碼的那部分的修正版本:

For each line in myTxtArr 
    tLine = Split(line, ",") 
    tLine(1) = Trim(tLine(1)) 
    If tLine(1) = "anotherstring" Then 
     MsgBox "match" 
    End If 
Next 
+1

'tLine = Split(tLine,「,」)==>'tLine = Split ,「,」)' –

+0

@ Ekkehard.Horner:謝謝。 DId在我從問題中複製的代碼中看不到那個錯誤。感謝您指出。固定。 –