Vbscript Trim 函数

Vbscript Trim function

我有一个读取逗号分隔文本文件的脚本,但是每当我对文件中提取的其中一个值使用 Trim(str) 时,它都不起作用...

我的文本文件:

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

我的脚本从未达到 "match",我不确定为什么。

Trim() 是 return 修剪字符串的函数。您的代码使用不当。您需要使用 returned 值:

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

或者使用另一个变量来存储值,并在比较中使用那个单独的变量,

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

或者直接在比较中使用函数return值,

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