2016-08-31 51 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在我从问题中复制的代码中看不到那个错误。感谢您指出。固定。 –