1

I'm having some problems executing the following in Excel VBA. The goal is to run an .sql file - the issue is with the Execute Shell sub I think.

I run:

Sub RunFile()
    Call ExecuteShell("C:\","LAPBTN1749","filename.sql")
End Sub

Sub ExecuteShell(path As String, hostname As String, file As String)
    Dim retval
    retval = Shell("SQLCMD -E -S " & hostname & "\SQLEXPRESS -i " & path & file, vbMinimizedFocus)
End Sub

It doesn't run, probably due to the quotes. If it is the quote, can someone explain how they work or tell me where I can find out because I've never properly understood this.

2
  • 1
    "It doesn't run" - what does it do? Commented Jul 30, 2015 at 17:20
  • Just that - it didn't appear to do anything. Adding the quotes in helped though as I had expected - many thanks. Commented Jul 31, 2015 at 8:20

2 Answers 2

1

I agree with @TimWilliams. I prefer to append Chr$(34) to a string because it means I don't have to count the number of quotes that I'm using. The code looks like:

Sub RunFile()
    Call ExecuteShell("C:\", "LAPBTN1749", "filename.sql")
End Sub

Sub ExecuteShell(path As String, hostname As String, file As String)
    Dim retval
    retval = Shell("SQLCMD -E -S " & Chr$(34) & hostname & "\SQLEXPRESS" & Chr$(34) & " -i " _
        & Chr$(34) & path & file & Chr$(34), vbMinimizedFocus)
End Sub
Sign up to request clarification or add additional context in comments.

Comments

1

If any of the passed parameters contain spaces then likely they need to be quoted in the call to Shell. Quotes in VBA are escaped by doubling them up:

Sub RunFile()
    Call ExecuteShell("C:\","LAPBTN1749","filename.sql")
End Sub

Sub ExecuteShell(path As String, hostname As String, file As String)
    Dim retval
    retval = Shell("SQLCMD -E -S """ & hostname & "\SQLEXPRESS"" -i """ & _
                   path & file & """", vbMinimizedFocus)
End Sub

If you're still having problems then try Debug.Printing the first Shell argument and running it "manually" at the command prompt.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.