2015-04-07 124 views
0

Heyho,我遇到了一个奇怪的问题。VBA执行一个.bat文件,但覆盖.bat文件中的一个cd

我在VBA执行这样一行:

Shell "path_to_my_bat\batname.bat" 

蝙蝠的内容很简单,以及:

cd c:\some_path\ 
copy *csv newfiles.txt 

它的作用是简单地采取所有的CSV目录并将它们合并为一个.txt文件,我将其用在宏的更下面。

问题是,因为我玩过一些vbs脚本,所以似乎我已经改变了shell命令的工作方式。

“cd”命令似乎被跳过或被某些东西覆盖,蝙蝠的实际第二部分在放入我的工作簿的目录中执行。 幸运的是,我有一个.csv躺在那里,否则我会没有注意到...

蝙蝠本身工作正常,如果我不从VBA运行它。

的vbs脚本我看起来像这样打(它应该打开一个文件,并在那里执行宏):

我想我重写了某种默认设置的,我不应该有修修补补... 除此之外,我没有做任何事情,我知道要改变一些事情。这个宏今天早上工作正常,但现在由于蝙蝠错误,它是没用的。

' Create a WshShell to get the current directory 
Dim WshShell 
Set WshShell = CreateObject("WScript.Shell") 

' Create an Excel instance 
Dim myExcelWorker 
Set myExcelWorker = CreateObject("Excel.Application") 

' Disable Excel UI elements 
myExcelWorker.DisplayAlerts = False 
myExcelWorker.AskToUpdateLinks = False 
myExcelWorker.AlertBeforeOverwriting = False 
myExcelWorker.FeatureInstall = msoFeatureInstallNone 

' Tell Excel what the current working directory is 
' (otherwise it can't find the files) 
Dim strSaveDefaultPath 
Dim strPath 
strSaveDefaultPath = myExcelWorker.DefaultFilePath 
strPath = WshShell.CurrentDirectory 
myExcelWorker.DefaultFilePath = strPath 

' Open the Workbook specified on the command-line 
Dim oWorkBook 
Dim strWorkerWB 
strWorkerWB = strPath & "\YourWorkbook.xls" 

Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB) 

' Build the macro name with the full path to the workbook 
Dim strMacroName 
strMacroName = "'" & strPath & "\YourWorkbook" & 
    "!Sheet1.YourMacro" 
on error resume next 
    ' Run the calculation macro 
    myExcelWorker.Run strMacroName 
    if err.number <> 0 Then 
     ' Error occurred - just close it down. 
    End If 
    err.clear 
on error goto 0 

oWorkBook.Save 

myExcelWorker.DefaultFilePath = strSaveDefaultPath 

' Clean up and shut down 
Set oWorkBook = Nothing 

' Don’t Quit() Excel if there are other Excel instances 
' running, Quit() will 
shut those down also 
if myExcelWorker.Workbooks.Count = 0 Then 
    myExcelWorker.Quit 
End If 

Set myExcelWorker = Nothing 
Set WshShell = Nothing 

如果有帮助,我运行Windows 8.1的64位与Excel 2010 64位 得到了完整的管理存取权限等

+0

你是从不同的驱动器上运行? – SLaks

回答

0

如果当前目录是在d:驱动器,然后cd c:\some_path\将设置目录为C:,但您当前的驱动器将保留在D:的某处。你需要告诉CMD.EXE真正改变它推动你在工作。

简单地改变你的命令

cd /d c:\some_path\ 

pushd c:\some_path\ 
+0

是解决问题的。谢谢! 我现在的问题是:为什么它首先工作。蝙蝠和xlsm总是位于不同硬盘上的不同目录中。 但是,我猜想问题解决了:) – Vaizard27