将VBS应用于当前目录中的文件

时间:2013-11-27 17:21:24

标签: excel batch-file vbscript

我有一些VBS代码用于将Excel格式应用于电子表格:

Set xlObj = CreateObject("Excel.Application")
Set xlFile = xlObj.WorkBooks.Open("C:\Documents and Settings\user\forms.xlsx")
xlObj.Application.DisplayAlerts = False
For Each Worksheet In xlFile.Worksheets
  dPriorWorkday = xlObj.Application.WorksheetFunction.WorkDay(Now, -1)
  Worksheet.Name = "Forms received " & Year(dPriorWorkday) & "-" & Right("0" & Month(dPriorWorkday),2) & "-" & Right("0" & Day(dPriorWorkday),2)
With Worksheet.Cells.Font
   .Name = "Arial"
   .Size = 8
End With
Next 
xlFile.Close True
xlObj.Quit

我使用.bat文件在.xlsx工作表上运行此VBS,所有3个文件都在同一目录中。

我要做的是更改VBS以将格式应用于与.bat和.vbs文件位于同一目录中的.xlsx文件,因此我可以删除直接文件路径“ C:\ Documents and Settings \ user \“

我试过了:

Workbooks.Open Filename:=ThisWorkbook.Path & "\forms.xlsx"

但它不起作用,我假设因为那是从工作簿本身调用的.vbs。

我可以使用类似的东西将.vbs应用到与.vbs相同的目录中的文件,而不使用完整的文件路径吗?

3 个答案:

答案 0 :(得分:4)

  

我要做的是更改VBS以将格式应用于与.bat和.vbs文件位于同一目录中的.xlsx文件,因此我可以删除直接文件路径“C:\ Documents and Settings \ user \“

如果所有文件都在同一目录中,请使用此

Set WshShell = CreateObject("WScript.Shell")
strCurDir = WshShell.CurrentDirectory

Set xlObj = CreateObject("Excel.Application")
Set xlFile = xlObj.Workbooks.Open(strCurDir & "\forms.xlsx")

有关CurrentDirectoy HERE

的更多信息

修改

Ekkehard.Horner的回复更贴切,可以处理从不同目录调用vba的情况。在这种情况下,CurrentDirectoy显然不会给出预期的路径。

答案 1 :(得分:2)

如果要可靠地选择“与.bat和.vbs文件相同的目录”(无论您调用脚本的文件夹或(accidential)更改为.CurrentDirectory),都应使用WScript.ScriptFullName:

Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim goWS : Set goWS = CreateObject("WScript.Shell")
Wscript.Echo "CD", goWS.CurrentDirectory
Wscript.Echo "FS", goFS.GetAbsolutePathName(".")
goWS.CurrentDirectory = "c:\temp"
Wscript.Echo "CD", goWS.CurrentDirectory
Wscript.Echo "FS", goFS.GetAbsolutePathName(".")
Wscript.Echo "SD", goFS.GetParentFolderName(WScript.ScriptFullName)

输出:

DNV35 C:\Documents and Settings\eh
cscript 31.vbs
CD C:\Documents and Settings\eh
FS C:\Documents and Settings\eh
CD c:\temp
FS C:\Temp
SD C:\Documents and Settings\eh

DNV35 C:\Documents and Settings\eh
cd ..

DNV35 C:\Documents and Settings
cscript eh\31.vbs
CD C:\Documents and Settings
FS C:\Documents and Settings
CD c:\temp
FS C:\Temp
SD C:\Documents and Settings\eh

答案 2 :(得分:0)

我的解决方案,一直对我有用。我将当前路径存储到名为cur的变量中,然后将其附加到我的excel名称中:

Set objShell = CreateObject("WScript.Shell")
Dim cur
cur = objShell.CurrentDirectory
WScript.Echo cur

ExcelMacroExample

Sub ExcelMacroExample() 

Dim xlApp 
Dim xlBook 
Dim xlsFile
xlsFile = cur & "\myExcel.xlsm"

Set xlApp = CreateObject("Excel.Application") 
Set xlBook = xlApp.Workbooks.Open(xlsFile) 
xlApp.Run "sheetname"
xlApp.Save
xlApp.Quit 

End Sub