解析CSV文本文件

时间:2016-02-09 17:04:46

标签: vbscript

我有以下需要使用VBScript解析的CSV文件。脚本的目的是匹配日期。

"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
"2YRCMT",.743300,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\rand.mahmwd\Desktop\index.txt", ForReading)

Do Until objTextFile.AtEndOfStream
    strLine = objTextFile.ReadLine()

    If InStr(strLine, strSearchFor) = 0 Then
        Set objFile = objFSO.CreateTextFile("C:\Users\rand.mahmwd\Desktop\error.txt")
        objFile.Write "date is not match" & vbCrLf
        Exit Do
    End If
Loop
objTextFile.Close

如果日期匹配,则始终创建error.txt

1 个答案:

答案 0 :(得分:0)

您的代码在以下条件下适用于我:

  • 输入文件必须是ANSI编码。
  • 文件中的所有日期必须是前一个工作日。
  • 该文件不得包含任何其他行,包括空行。
  • 该脚本仅在工作日运行。
  • 前一个工作日不在上个月。

最后一个前提条件是由于脚本中的错误。您可以计算当前日期(DatePart("m", Date)DatePart("yyyy", Date))的月份和年份,但是从上一个工作日的日期开始计算的日期(DatePart("d", Date-3)DatePart("d", Date-1))。这可以通过对所有计算使用相同的日期来修复:

If WeekDay(Date) = 2 Then
    MyDate = Date - 3
Else
    MyDate = Date - 1
End If

strSearchFor = Right("0" & DatePart("m", MyDate), 2) & "/" & _
               Right("0" & DatePart("d", MyDate), 2) & "/" & _
               DatePart("yyyy", MyDate)