【发布时间】:2015-04-07 17:01:02
【问题描述】:
嘿嘿,我遇到了一个奇怪的问题。
我在我的 VBA 中执行这样的一行:
Shell "path_to_my_bat\batname.bat"
bat的内容也很简单:
cd c:\some_path\
copy *csv newfiles.txt
它所做的只是获取目录中的所有 csv,并将它们合并到一个 .txt 中,我在宏中进一步使用它。
问题是,因为我玩过一些 vbs 脚本,所以我似乎改变了 shell 命令的工作方式。
“cd”命令似乎被跳过,或被某些东西覆盖,bat 的实际第二部分是在我的 Workbook 所在的目录中执行的。 幸运的是,我有一个 .csv 文件,否则我不会注意到...
如果我不从 VBA 运行它,它本身就可以正常工作。
我玩过的 vbs 脚本看起来像这样(它应该打开一个文件并在其中执行一个宏):
我想我重写了一些我不应该修改的默认设置... 除此之外,我没有做任何我知道的改变某些事情的事情。宏今天早上运行良好,但现在由于 bat 错误而无用。
' 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 位 拥有完整的管理员权限等。
【问题讨论】:
-
您是否从不同的驱动器运行?
标签: vba excel batch-file vbscript excel-2010