VBScript用户输入变量

时间:2013-08-12 07:51:14

标签: excel csv vbscript

我正在创建一个用于拆分csv文件的脚本,我想让用户输入文件被拆分为新文件的时间间隔。

我遇到的问题是,当我输入间隔时,它不是分裂,但是如果我硬编码它的值就会分裂。

Option Explicit

Const ForReading = 1
Const ForWriting = 2

Dim objFSO, objInputFile, objOutputFile
Dim intLine, intFile
Dim strHeaders
Dim strInputFile, strOutputPrefix, strLine
Dim MyDate
Dim userSplit
Dim split

'strInputFile = InputBox("Enter file location")
strInputFile = "H:\VBS\domS_CUST.csv"
strOutputPrefix = strInputFile & DatePart("yyyy", Now) & "-" & DatePart("m", Now) & "-" & DatePart("d", Now) 


intFile = 1
intLine = 0

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objInputFile = objFSO.OpenTextFile(strInputFile, ForReading)

If (objInputFile.AtEndOfStream = True) Then
  ' The file is empty
  WScript.Quit 1
End If

strHeaders = objInputFile.ReadLine

userSplit = InputBox("Enter when you want to split")

Do While (objInputFile.AtEndOfStream = False)

split = userSplit

  strLine = objInputFile.ReadLine

  If (intLine <= 0) Then
    Set objOutputFile = objFSO.CreateTextFile(strOutputPrefix & "_" & intFile & ".csv", True)
    objOutputFile.WriteLine strHeaders

    intLine = 1
  End If

  objOutputFile.WriteLine strLine


  If (intLine >= split) Then
    objOutputFile.Close
    Set objOutputFile = Nothing

    intFile = intFile + 1
    intLine = 0
  Else
    intLine = intLine + 1
  End If
Loop 

输入是这一行:

userSplit = InputBox("Enter when you want to split")

我似乎无法将其分解为此值,任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:2)

您的代码中有On Error Resume Next未显示,否则为

split = userSplit

会引发错误

  

非法转让:'拆分'

split是内置函数的名称,因此不能用作变量名。这也是完全没必要的,因为您可以简单地使用userSplit而不将其值分配给另一个变量。


更正:正如Ekkehard.Horner在评论中指出的那样,Dim split取代了内置函数定义,因此不会产生错误。


但是,您的代码无法正常工作的主要原因是InputBox函数返回字符串值。要使intLine的比较正常工作,您需要将字符串转换为整数或长整数:

userSplit = CLng(InputBox("Enter when you want to split"))
...
If (intLine >= userSplit) Then

你应该至少添加一个检查来处理用户按下“取消”的情况:

userSplit = CLng(InputBox("Enter when you want to split"))
If userSplit <= 0 Then WScript.Quit 1

此外,通过使用Line属性,您的代码可以简化为:

filename = "H:\VBS\domS_CUST.csv"

Set fso = CreateObject("Scripting.FileSystemObject")
Set infile = fso.OpenTextFile(filename)

prefix  = fso.BuildPath(fso.GetParentFolderName(filename) _
  , fso.GetBaseName(filename) & "_" & Year(Now) & "-" _
  & Right("0" & Month(Now), 2) & "-" & Right("0" & Day(Now), 2) & "_")

userSplit = CLng(InputBox("Enter when you want to split"))
If userSplit <= 0 Then WScript.Quit 1

Do Until infile.AtEndOfStream
  If infile.Line = 1 Then
    headers = infile.ReadLine
  Else
    If (infile.Line - 2) Mod userSplit = 0 Then
      If infile.Line > 2 Then outfile.Close
      Set outfile = fso.CreateTextFile _
        (prefix & (infile.Line - 2) \ userSplit + 1 & ".csv", True)
      outfile.WriteLine headers
    End If
    outfile.WriteLine infile.ReadLine
  End If
Loop
outfile.Close