(Shell功能)VBA中需要文件路径吗? [英] Is file path needed in (Shell Function) VBA?
问题描述
我不想包含整个文件路径,因为我不想限制用户某个文件夹在每个计算机上的某个位置。
我有以下代码调用可执行文件,这可以正常工作:
错误恢复下一步Shell(C:\Users\elwany\Desktop\Myfolder\Myfile.exe)
如果Err<> 0然后
MsgBox无法启动应用程序,vbCritical,错误
如果
结束Sub
我的问题/问题是
我将可执行文件+将VBA项目的Excel文件放在同一文件夹(Myfolder)中,然后我修改代码:
Sub MyExe()
On Error Resume Next
Shell(Myfile.exe)
如果Err<> 0然后
MsgBox无法启动应用程序,vbCritical,错误
如果
结束Sub
有时它有效,有时它不!
例如,昨天我运行了VBA代码,它工作。今天我打开相同的Excel文件,同一个文件夹,一切都一样,它给出无法启动应用程序错误msg !!
- 是
- 为什么有时候会有效,有时候不行?
- 添加了文件路径绝对是必须的?
可以
- 按照我之前对您的问题的评论使用
ChDir
-
使用
Dir
来验证myfile.exe
是否需要成为。此方法不需要错误处理来处理丢失的文件。Sub TestB()
Dim strPath As String
strPath = Dir(c:\temp\myfile.exe)
如果Len(strPath)> 0然后
Shell strPath
Else
MsgBoxPath is not exist
End If
End Sub
Sub TestA()
On Error Resume Next
'使用主机工作簿路径
'ChDir ThisWorkbook.Path
'设置路径
ChDirC:\temp
Shell(Myfile.exe)
如果Err<> 0然后
MsgBox无法启动应用程序,vbCritical,错误
Else
MsgBoxsucess!,vbOKOnly
End If
End Sub
I have a Matlab-generated executable file, Myfile.exe to call from excel-vba. I learned (Shell Function) is what I need to use.
I don't want to include the whole file path as I do not want to restrict the user to a certain folder in a certain location on each computer.
I have the following code to call the executable, which works fine:
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
My problem/question is I put the executable + the Excel file with the VBA project in the same folder (Myfolder), and then I modify the code to:
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
Sometimes it works, sometimes it doesn't!
For example, yesterday I ran the VBA code, it worked. Today I opened the same Excel file, same folder, same everything, it gives "Can't Start Application" error msg!!
- Is it not okay to remove the file path even if I have everything in one folder?
- Why does it sometimes work, sometimes not?
- Is adding the file path absolutely mandatory?
As you have enquire further about different directories note that you can either
- Use
ChDir
as per my earlier comment to your question Use
Dir
instead to validate thatmyfile.exe
is where it needs to be. This method doesn't need error handling to handle the file being missing.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功能)VBA中需要文件路径吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!