我有一个 Matlab 生成的可执行文件,Myfile.exe,可以从 excel-vba 调用。我了解到(Shell Function)是我需要使用的。
我不想包含整个文件路径,因为我不想将用户限制到每台计算机上特定位置的特定文件夹。
我有以下代码来调用可执行文件,效果很好:
Sub MyExe()
On Error Resume Next
Shell ("C:\Users\elwany\Desktop\Myfolder\Myfile.exe")
If Err <> 0 Then
MsgBox "Can't start the application.", vbCritical, "Error"
End If
End Sub
我的问题是 我将可执行文件+ Excel 文件与 VBA 项目放在同一文件夹(Myfolder)中,然后将代码修改为:
Sub MyExe()
On Error Resume Next
Shell ("Myfile.exe")
If Err <> 0 Then
MsgBox "Can't start the application.", vbCritical, "Error"
End If
End Sub
有时有效,有时无效!
例如,昨天我运行了 VBA 代码,它有效。今天我打开相同的 Excel 文件,相同的文件夹,相同的一切,它给出了“无法启动应用程序”错误消息!!
- 即使我将所有内容都放在一个文件夹中,是否也可以删除文件路径?
- 为什么有时有效,有时无效?
- 添加文件路径是绝对强制的吗?
最佳答案
当您进一步询问不同的目录时,请注意您可以
- 按照我之前对您问题的评论使用
ChDir
使用
Dir
来验证myfile.exe
是否位于其需要的位置。此方法不需要错误处理来处理丢失的文件。Sub TestB() Dim strPath As String strPath = Dir("c:\temp\myfile.exe") If Len(strPath) > 0 Then Shell strPath Else MsgBox "Path doesn't exist" End If End Sub Sub TestA() On Error Resume Next 'use the host workbook path ' ChDir ThisWorkbook.Path 'set path here ChDir "C:\temp" Shell ("Myfile.exe") If Err <> 0 Then MsgBox "Can't start the application.", vbCritical, "Error" Else MsgBox "sucess!", vbOKOnly End If End Sub
关于shell - (Shell函数)VBA中需要文件路径吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8773678/