首页 > 解决方案 > 无法获取 .vbs 文件中的当前目录

问题描述

我编写了一个 Visual Basic 脚本来执行 Excel 宏。我想动态设置 .xlsm 文件的位置。我使用 FileSystemObject 来获取当前目录。它返回 C:\Windows\System32 但我需要 .vbs 文件所在的目录。

我尝试使用 FileSystemObject 和 WScript 获取当前目录但没有成功。

' 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)

预期的行为是打开 Excel 文件。但我收到一个错误:

错误

标签: vbscript

解决方案


您将当前工作目录与脚本的位置混淆了。两者并不相同。

其中任何一个都会为您提供当前的工作目录

CreateObject("WScript.Shell").CurrentDirectory
CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")

这将为您提供脚本的位置

CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)

推荐阅读