2016-02-09 65 views
1

將下面的.TXT文件讀入VBS FileSystemObject。我正在嘗試搜索所有匹配的日期,否則我需要將它們放在「error.txt」文件中。但是,當我在下面運行我的代碼時,它始終將匹配放在error.txt文件中,並且不會跳過匹配的日期。讀取文本並匹配文本文件中的所有日期,否則將值寫入error.txt文件

爲什麼日期不匹配?

輸入:

"LIRRR 1M",.412900,02/08/2016 
"LIRRR 3M",.222700,02/08/2016 
"LIRRR 6M",.333200,02/08/2016 
"LIRRR12M",1.1333300,02/08/2016 
"FEDFRRRR",.333000,02/08/2016 
"CCC 1YR",.550330,02/08/2016 
"5YRCMT",1.2503300,02/08/2016 
"10YRCMT",1.860000,02/08/2016 

這裏是我寫的代碼:

On error resume next 
Const ForReading = 1 
Dim strSearchFor 
Dim MyDate, MyWeekDay 
MyDate = Date ' Assign a date. 
MyWeekDay = Weekday(MyDate) 
If MyWeekDay = 2 then 
    strSearchFor =Right("0" & DatePart("m",Date), 2)&"/"&Right("0" & DatePart("d",Date-3), 2)&"/"&DatePart("yyyy",Date) 
Else 
    strSearchFor =Right("0" & DatePart("m",Date), 2)&"/"&Right("0" & DatePart("d",Date-1), 2)&"/"&DatePart("yyyy",Date) 
End If 
Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objTextFile = objFSO.OpenTextFile("C:\Users\Desktop\index.txt", ForReading) 
do until objTextFile.AtEndOfStream 
    strLine = objTextFile.ReadLine() 

    If InStr(strLine, strSearchFor) <> 0 then 

    Set objFile = objFSO.CreateTextFile("C:\Users\Desktop\pass.txt") 
     objFile.Write "date is match"& vbCrLf 

    Else 
     Set objFile = objFSO.CreateTextFile("C:\Users\Desktop\error.txt") 
     objFile.Write "date is not match"& vbCrLf 
    End If 
loop 
objTextFile.Close 

回答

0

爲什麼不使用正則表達式來獲得,似乎是日期字符串的一部分並使用IsDate函數來驗證它?

Option Explicit 
Dim arrLines,i 
arrLines = ReadFile("./input.txt","byline") 
For i=LBound(arrLines) to UBound(arrLines) 
    wscript.echo FormatOutput(arrLines(i)) 
Next 
'********************************************* 
Function FormatOutput(s) 
    Dim re, match 
    Set re = New RegExp 
    re.Pattern = "[\d]+[\/-][\d]+[\/-][\d]+" 
    re.Global = True 
    For Each match In re.Execute(s) 
     if IsDate(match.value) then 
      FormatOutput = CDate(match.value) 
      Exit For 
     end if 
    Next 
    Set re = Nothing 
End Function 
'********************************************* 
Function ReadFile(path,mode) 
    Const ForReading = 1 
    Dim objFSO,objFile,i,strLine 
    Set objFSO = CreateObject("Scripting.FileSystemObject") 
    Set objFile = objFSO.OpenTextFile(path,ForReading) 
    If mode = "byline" then 
     Dim arrFileLines() 
     i = 0 
     Do Until objFile.AtEndOfStream 
      Redim Preserve arrFileLines(i) 
      strLine = objFile.ReadLine 
      strLine = Trim(strLine) 
      If Len(strLine) > 0 Then 
       arrFileLines(i) = strLine 
       i = i + 1 
       ReadFile = arrFileLines 
      End If 
     Loop 
     objFile.Close 
    End If 
    If mode = "all" then 
     ReadFile = objFile.ReadAll 
     objFile.Close 
    End If 
End Function 
'***************************************************************** 
+0

謝謝哈克! – Rand

+0

@Rand不要忘記接受它作爲anwser和upvote它! – Hackoo

相關問題