问题
I write a Visual Basic Script to execute an Excel Macro. I want to set the location of .xlsm file dynamically. I use FileSystemObject to get the current directory. It returns C:\Windows\System32 but I need the directory where the .vbs file is located.
I tried to get the current directory with FileSystemObject and WScript without success.
' Create a FileSystemObject to get the current directory
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
strPath = fso.GetAbsolutePathName(".")
myExcelWorker.DefaultFilePath = strPath
' Open the Workbook specified on the command-line
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\Data center Wattsight long term.xlsm"
Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)
The expected behaviour is to open the Excel file. But I get an error:
回答1:
You're confusing the current working directory with the location of your script. The two are not identical.
Either of these will give you the current working directory:
CreateObject("WScript.Shell").CurrentDirectory
CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
This will give you the location of the script:
CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
来源:https://stackoverflow.com/questions/57674965/cannot-get-the-current-directory-in-vbs-file