Opening a File whose Name Contains a Space
Asked Answered
H

1

8

I have some simple Excel VBA code that opens non-Excel files like:

Sub scriptTest()
    Set objshell = CreateObject("Wscript.Shell")
    objshell.Run ("C:\TestFolder\Book1.pdf")
    Set objshell = Nothing
End Sub

Running this opens the file in the Acrobat Reader. However if I try to open a file whose name contains a space character like:

Sub scriptTest()
    Set objshell = CreateObject("Wscript.Shell")
    objshell.Run ("C:\TestFolder\Bo ok1.pdf")
    Set objshell = Nothing
End Sub

I get:

enter image description here

Both files open fine if I use the Run command from the Windows Start menu. How can I overcome this problem ??

Hose answered 5/10, 2017 at 19:29 Comment(6)
@MykolaShchetinin Thanks for the suggestion, but neither forward slash or backslash had any effect.Patriarchy
@YowE3K PERFECT! Post an answer and I'll accept it.Patriarchy
Why use COM in VBA at all, theres in no need for late binding this stuff when you have full access to the Windows APIs.Smalls
@Lankymart Good idea! I will pursue it.Patriarchy
@Gary'sStudent CreateProcess function would be where to start.Smalls
@Lankymart Thank you !Patriarchy
S
12

When executing the statement objshell.Run ("C:\TestFolder\Bo ok1.pdf"), you are asking the shell to execute the command

C:\TestFolder\Bo ok1.pdf

This is interpreted as being a request to execute the program C:\TestFolder\Bo.exe with a parameter of ok1.pdf.

You actually want the shell to execute the command

"C:\TestFolder\Bo ok1.pdf"

where the quotation marks are used by the command interpreter to "group" parts of the command together.

To obtain that command, you need to execute the statement

objshell.Run """C:\TestFolder\Bo ok1.pdf"""
Strep answered 5/10, 2017 at 19:44 Comment(2)
Wow, 6 votes for pointing out when you want to escape a quoted string you need to double the quotes. Seriously, this hasn't been answered before?Smalls
@Lankymart It wasn't actually that the quotation marks needed to be escaped, it was that the quotation marks needed to be used. (If you find a good duplicate, please feel free to close the question, and ping me so I can delete the answer.)Strep

© 2022 - 2024 — McMap. All rights reserved.