Open Relative path in VBS with OpenText and SaveAs

2019-09-02 12:09发布

ok so I have some code in a vbs file, where basically I want to open a CSV file. Perform some changes (I can work that out later) and then save it as an xls. The code works flawlessly when run with a fully qualified file path. However I need the file path to be relative. The files will always be opened and saved to the same path the script is run from. Ive looked at GetParentFolderName and GetAbsolutePathName. However I cant figure how to call the fully qualified path in the text. I've tried just putting the variable where the file name is with and without quotes, appended it with a period.

Any example on building the function or whatever, and then calling it in the code below would be a huge help.

Dim myXL
Const xlDelimited = 1
Const xlWorkbookNormal = -4143

Set myXL=CreateObject("Excel.Application")
myXL.Visible=False
myXL.WorkBooks.OpenText "file.csv", , , xlDelimited, , , , , True 

myXL.DisplayAlerts=False

MORE CODE WILL GO HERE

myXL.ActiveWorkbook.SaveAs "new_file.xls", xlWorkbookNormal 

myXL.DisplayAlerts=True

myXL.ActiveWorkbook.Close False
myXL.Quit

Set myXL = Nothing

2条回答
放荡不羁爱自由
2楼-- · 2019-09-02 12:41

You can get the path of your script by using this code that i Found at an answer about Relative Path

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

p should be the path to your script you can then edit "file.csv" to p & "\file.csv" and so.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-09-02 12:48

To point out/emphasize that

  1. you should never use string concatenation to build pathes; .BuildPath() is the way to go
  2. "relative path" needs a clear "relative to what" specification
  3. VBScript's concatenation operator is & not . (dot/period)

:

>> f = WScript.ScriptFullName
>> n = WScript.ScriptName
>> p = goFS.GetParentFolderName(f)
>> a = goFS.GetAbsolutePathName(n)
>> c = goWS.CurrentDirectory
>> WScript.Echo "c", c
>> WScript.Echo "p", p
>> WScript.Echo "?", p & n
>> Wscript.Echo "a", a
>> WScript.Echo "!", goFS.BuildPath(p, n)
>>
c C:\Documents and Settings\eh
p M:\bin
? M:\binivbs.wsf
a C:\Documents and Settings\eh\ivbs.wsf
! M:\bin\ivbs.wsf
查看更多
登录 后发表回答