我有一个在VBA中运行良好的功能,但显然不在VBS中。
我相信我必须将其转换为使用FSO? 但我真的不知道如何开始这样做。
它似乎也不喜欢我指定参数和函数数据类型?
我的功能是:
Function CSV_1304_USA_date_convertor(ByVal InputFile As String, ByVal OutputFile As String) As Boolean
CSV_1304_USA_date_convertor = False 'set as failed until the end
On Error GoTo error1 'error trapping
Dim ThisString As String, vArray As Variant 'set up the variables
Open InputFile For Input As #1 'open the input file
Open OutputFile For Output As #2 'open/create the output file
Line Input #1, ThisString 'copy the first row (headings)
Print #2, ThisString
While Not EOF(1) 'loop for each row
Line Input #1, ThisString 'read in the row
vArray = Split(ThisString, ",") 'split into an array
For x = 0 To UBound(vArray) 'for each field in the array
If Mid(vArray(x), 3, 1) = "/" And Mid(vArray(x), 6, 1) = "/" Then 'if it is a date (ISDATE doesnt work as they are American!)
vArray(x) = Mid(vArray(x), 4, 2) & "/" & Left(vArray(x), 2) & "/" & Right(vArray(x), 2) 'switch the day and month around
End If
Next x
Print #2, Join(vArray, ",") 'join array back into comma delim text and put the row into the output file
Wend
Close #1 'close the input file
Close #2 'close the output file
CSV_1304_USA_date_convertor = True 'success!
Exit Function 'end
error1:
'the function will return as false
On Error Resume Next 'ignore any further errors
Close #1 'close the input file, if possible
Close #2 'close the output file, if possible
End Function
答案 0 :(得分:0)
好的,经过大量的试验和错误,我发现了它。 事实证明,VBS需要有很多不同的东西。
以下是我的最终代码,以防其他人使用:
Function CSV_1304_USA_date_convertor(InputFile,OutputFile)
CSV_1304_USA_date_convertor = False 'set as failed until the end
'setup variables etc
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim ThisString , vArray , f1 , f2, fso
Set fso = CreateObject("Scripting.FileSystemObject")
'open and create text files
Set f1 = fso.OpenTextFile(InputFile, ForReading, True)
Set f2 = fso.CreateTextFile(OutputFile)
'loop for each row
While f1.AtEndOfStream <> True
ThisString = f1.Readline 'read in the row
vArray = Split(ThisString, ",") 'split into an array
For x = 0 To UBound(vArray) 'for each field in the array
If Mid(vArray(x), 3, 1) = "/" And Mid(vArray(x), 6, 1) = "/" Then 'if it is a date
vArray(x) = Mid(vArray(x), 4, 2) & "/" & Left(vArray(x), 2) & "/" & Right(vArray(x), 2) 'switch the day and month around
End If
Next
f2.WriteLine Join(vArray, ",") 'join array back into comma delim text and put the row into the output file
Wend
'finish up
f1.Close 'close the input file
f2.Close 'close the output file
Set f1 = Nothing
Set f2 = Nothing
Set fso = Nothing
CSV_1304_USA_date_convertor = True 'success!
End Function