3

我有一个脚本可以读取逗号分隔的文本文件,但是每当我在文件中提取的值之一上使用 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

我的脚本从未达到“匹配”,我不知道为什么。

4

1 回答 1

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
于 2016-08-31T20:26:25.277 回答