(Shell Function)VBA中需要文件path吗?
我有一个Matlab生成的可执行文件,从excel-vba调用Myfile.exe 。 我学到了(Shell函数)是我需要使用的。
我不希望包含整个文件path,因为我不想将用户限制在每台计算机上某个位置的某个文件夹中。
我有以下代码来调用可执行文件,它工作正常:
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文件,相同的文件夹,相同的一切,它给“无法启动应用程序”错误消息!
- 即使我已经在一个文件夹中的所有东西都删除文件path是不行吗?
- 为什么它有时会工作,有时不是?
- 是添加文件path绝对强制?
正如你有进一步查询不同的目录注意,你可以
- 根据我之前对你的问题的评论使用
ChDir
-
使用
Dir
来validationmyfile.exe
是它需要的地方。 此方法不需要error handling来处理丢失的文件。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
如果在没有指定path的情况下运行这样的shell,它将从Active Directory运行。 活动目录取决于操作系统,而不是Excel / VBA(除非您明确地设置)
试试这个
Sub MyExe() On Error Resume Next Shell (ThisWorkbook.Path & "\Myfile.exe") If Err <> 0 Then MsgBox "Can't start the application.", vbCritical, "Error" End If End Sub