无法使用当前的Folder目录运行vbs

时间:2018-03-08 15:36:33

标签: vbscript

这是我的第一次vbs体验。 我试着保持我的问题简短。 当我使用.bat:

运行时,这个有效
Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
 Dim xlApp 
 Dim xlBook 
 Set xlApp = CreateObject("Excel.Application") 
 Set xlBook = xlApp.Workbooks.Open("C:\.....\RunScript.xlsm", 0, 
 True) 
 xlApp.Run "Auto_Open"
 xlApp.Quit 
 Set xlBook = Nothing 
 Set xlApp = Nothing 
End Sub 

这个有效(用我的文件显示我的核心当前目录):

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
sScriptDir = oFSO.GetParentFolderName(WScript.ScriptFullName)
Wscript.Echo sScriptDir & "\RunScript.xlsm"

但是,如果我将它们组合在一起,无法正常工作

Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
 Dim xlApp 
 Dim xlBook 

 Dim oFSO
 Set oFSO = CreateObject("Scripting.FileSystemObject")
 sScriptDir = oFSO.GetParentFolderName(WScript.ScriptFullName)
 Set fileDirectory = sScriptDir & "\RunScript.xlsm"

 Set xlApp = CreateObject("Excel.Application") 
 Set xlBook = xlApp.Workbooks.Open(fileDirectory, 0, 
 True) 
 xlApp.Run "Auto_Open"
 xlApp.Quit 
 Set xlBook = Nothing 
 Set xlApp = Nothing 
End Sub 

1 个答案:

答案 0 :(得分:0)

像我说的那样,谢谢戴夫。这样可行。 但是我发现了另一个问题,现在 RunScript.xlsm 中的vb A 此代码适用,之前为 S

Sub Auto_Open()

Application.DisplayAlerts = False
ActiveWorkbook.RefreshAll
ActiveWorkbook.Save
    ActiveWorkbook.SaveAs Filename:= _
        "C:\...\MyCSV.csv" _
        , FileFormat:=xlCSV, CreateBackup:=False
Application.DisplayAlerts = True
ThisWorkbook.Saved = True
Application.Quit
End Sub

但是,如果我在路径上更改,那么当我运行 RunScript.xlsm 时,它只是工作,而不是在我运行 vbS 时:

Sub Auto_Open()

Application.DisplayAlerts = False
ActiveWorkbook.RefreshAll
ActiveWorkbook.Save

Dim relativePath As String
relativePath = Application.ActiveWorkbook.path & "\MyCSV.csv"

ActiveWorkbook.SaveAs Filename:=relativePath, FileFormat:=xlCSV, CreateBackup:=False

Application.DisplayAlerts = True
ThisWorkbook.Saved = True
Application.Quit
End Sub

我认为这是因为ActiveWorkbook,我已经尝试了ThisWorkbook,我在没有应用程序的情况下尝试过。