简体   繁体   English

带变量和空格的VBA Shell命令

[英]VBA Shell command with variables and spaces

In a Microsoft Outlook macro, I'm trying to use a Shell() call to open an Excel spreadsheet (whose filepath is referenced by my templatePath variable). 在Microsoft Outlook宏中,我尝试使用Shell()调用打开Excel电子表格(其文件路径由我的templatePath变量引用)。 I keep getting syntax errors from the editor and "file not found" errors when executing it. 我不断从编辑器中获取语法错误,并在执行它时出现“找不到文件”错误。

I started with the following line: 我从以下几行开始:

Shell ("""C:\Program Files (x86)\Microsoft Office\Office16\EXCEL.EXE"" ""C:\Users\My_Username\Desktop\My_Folder\Request Template.xlsx"""), vbNormalFocus

It opens the appropriate file just fine; 它会打开适当的文件; I just don't know the proper syntax to use the templatePath variable instead of hard-coding the path to the spreadsheet. 我只是不知道使用templatePath变量的正确语法,而不是硬编码电子表格的路径。 I've seen questions similar to this, but none seemed to fit my situation closely enough. 我见过类似的问题,但是似乎没有一个问题与我的情况十分接近。 Any help would be greatly appreciated! 任何帮助将不胜感激!

This should work: 这应该工作:

Dim templatePath As String

templatePath = "C:\Users\My_Username\Desktop\My_Folder\RequestTemplate.xlsx"

Shell ("""C:\Program Files (x86)\Microsoft Office\Office16\EXCEL.EXE"" """ & templatePath & """"), vbNormalFocus

If your template resides in the Application.TemplatesPath and you just want to specify the file name then use: 如果您的模板位于Application.TemplatesPath而您只想指定文件名,则使用:

templatePath = Application.TemplatesPath & "RequestTemplate.xlsx"

A more adjustable version: 更加可调的版本:

Dim templatePath As String
Dim programPath As String
Dim templateName As String

templateName = "RequestTemplate.xlsx"
templatePath = Application.TemplatesPath
programPath = "C:\Program Files (x86)\Microsoft Office\Office16\EXCEL.EXE"

Shell ("""" & programPath & """" & " " & """" & templatePath & templateName & """"), vbNormalFocus

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM