【问题标题】:Vbscript Trim functionVBScript 修剪功能
【发布时间】:2017-01-08 13:18:54
【问题描述】:

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

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

【问题讨论】:

  • 您是否遇到了数组越界错误?
  • 没有错误,只是没有修剪
  • trim("some string, anotherstring, onelaststring") 永远不会等于 "anotherstring"。也许您想在“,”上拆分行?
  • 很抱歉我没有包含我的代码的那部分,我更新了它。
  • 啊啊啊。好的。很有道理。

标签: vbscript whitespace space trim blank-line


【解决方案1】:

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

【讨论】:

  • tLine = Split(tLine, ",") ==> tLine = Split(line, ",")
  • @Ekkehard.Horner:谢谢。我从问题中复制的代码中没有看到该错误。感谢您指出。固定。
猜你喜欢
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 2016-12-11
  • 2014-07-19
  • 1970-01-01
相关资源
最近更新 更多