更改vbs脚本的输出目录

时间:2013-07-08 15:37:59

标签: vbscript

我编写了一个脚本,它的作用是将文件放入文件夹,然后自动将文件转换为制表符分隔文件。然后它创建一个名为“output”的新文件夹。我需要做的是能够将它保存到指定的位置。下面是我写的代码的副本。

Dim saveDirBase

set fso = CreateObject("Scripting.FileSystemObject")
set shell = CreateObject("WScript.Shell")
set objExcel = CreateObject("Excel.Application")

set top = fso.GetFolder(shell.CurrentDirectory)
saveDirBase = top & "\" & "output"

Sub TraverseFolders(path)
set folder = fso.GetFolder(path)

XL2Tab(folder)

For each item in folder.SubFolders
If item.Path <> saveDirBase Then
Call TraverseFolders(item.Path)
End If
Next
set folder = Nothing
End Sub

Sub XL2Tab(folder)
Dim saveDir
set files = folder.Files

If folder.Name <> top.Name Then
saveDir = saveDirBase & "\" & folder.Name
Else
saveDir = saveDirBase
End If

If fso.FolderExists(saveDir) = False Then
fso.CreateFolder(saveDir)   
End If

For each file In files
If file.Name <> Wscript.ScriptName Then
objExcel.Application.DisplayAlerts = False
Set objWorkbook = objExcel.Workbooks.open(folder.Path & "\" & file.Name)   
objWorkbook.SaveAs saveDir & "\" & file.Name & ".txt", -4158    
objWorkbook.close
objExcel.Application.DisplayAlerts = True
End If
Next
End Sub

If fso.FolderExists(saveDirBase) = False Then
fso.CreateFolder(saveDirBase)   
End If

Call TraverseFolders(top)

1 个答案:

答案 0 :(得分:0)

如果您的问题是如何提示用户输出文件夹,请求用户输入的最简单方法是InputBox

top = InputBox("Enter base folder.", WScript.ScriptName)

但这需要一些输入验证:

If IsEmpty(top) Then
  WScript.Echo "User pressed [Cancel]."
  WScript.Quit 1
ElseIf top = "" Then
  WScript.Echo "Empty path."
  WScript.Quit 1
ElseIf Not fso.FolderExists(top) Then
  WScript.Echo top & " doesn't exist. Creating ..."
  fso.CreateFolder(top)
End If
...

更好的方法是使用Shell.BrowseForFolder方法:

Set os = CreateObject("Shell.Application")
basedir = os.Namespace("C:\").Self.Path
Set fldr = os.BrowseForFolder(0, "Select folder:", &h10&, basedir)

If fldr Is Nothing Then
  WScript.Echo "User pressed [Cancel]."
  WScript.Quit 1
End If

top = fldr.Self.Path
...