问题
I have a vbscript that opens a workbook and runs a procedure in the module1 of the workbook, then closes the workbook. Works great. But here's the thing. The path to the workbook is hard coded, like this:
Set xlBook = xlApp.Workbooks.Open("E:\FolderName\WorkbookName.xlsm", 0, True)
I don't mind requiring the user to have the script and the workbook in the same folder, and requiring that they not change the name of the workbook file, but I'd like to just substitute the hard coded path with something dynamic, like:
Set xlBook = xlApp.Workbooks.Open(VBSPath & "\WorkbookName.xlsm", 0, True)
So the path is whatever is the path of the script.
Is that possible? Any other ideas?
tod
回答1:
You can try like that :
VBSPath = Left(WScript.ScriptFullName,(Len(WScript.ScriptFullName) - (Len(WScript.ScriptName) + 1)))
msgbox VBSPath
回答2:
VBScript provides various information about the current script and host process via properties of the WScript object, among them:
ScriptFullName: The full path to the current script.ScriptName: The filename of the current script.
You can derive the script folder from the ScriptFullName property in a number of ways, e.g.
By using the GetParentFolder method:
Set fso = CreateObject("Scripting.FileSystemObject") dir = fso.GetParentFolderName(WScript.ScriptFullName)By using the Len and Left functions:
dir = Left(WScript.ScriptFullName, Len(WScript.ScriptFullName)-Len(WScript.ScriptName))By using the InStrRev and
Leftfunctions:dir = Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))By using the Split and Join functions:
a = Split(WScript.ScriptFullName, "\") a(UBound(a)) = "" dir = Join(a, "\")By using the Replace function:
dir = Replace(WScript.ScriptFullName, WScript.ScriptName, "")Note that this approach might prove problematic if (for whatever reason) the script name appears somewhere else in the full name of the script as well (e.g.
C:\script.vbs\script.vbs).
回答3:
I figured out one solution, very similar to what has been posted here.
I created a WScript.Shell object:
Set WshShell = CreateObject("WScript.Shell")
Then I used the CurrentDirectory as the path of the workbook:
Set xlBook = xlApp.Workbooks.Open(WshShell.CurrentDirectory & "\WorkbookName.xlsm", 0, True)
Works!
来源:https://stackoverflow.com/questions/41577952/replace-hard-code-path-with-dynamic-path-of-vbscript