Shell command excel vba - vba

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.

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

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.

Related

Shell to move file returns Invalid Procedure call or Argument

Using Windows 10
Dim logPathSource As String
Dim logFileSource As String
Dim logPathDest As String
Dim logFileDest As String
logPathSource = "D:\Users\ian_abbott\AppData\Local\Temp\Data Capture Log\"
logFileSource = "moving180827_160818.csv"
logPathDest = "\\ussantapps332\DataCapture\tmp\"
logFileDest = "2018-08-27_16,08,28UKASIABBOTTL10-Ian_Abbott_TESTlogdata.csv"
Shell "cmd /c move """ & logPathSource & logFileSource & """ """ & logPathDest & logFileDest & """", vbHide
Putting the PathName for the Shell command into the Immediate Window, I get:
cmd /c move "D:\Users\ian_abbott\AppData\Local\Temp\Data Capture Log\moving180827_160818.csv" "\\ussantapps332\DataCapture\tmp\2018-08-27_16,08,28UKASIABBOTTL10-Ian_Abbott_TESTlogdata.csv"
If I copy/paste that into Command Prompt, the file is moved and renamed successfully, if I run it from VBA I get
Run-time error '5':
Invalid procedure call or argument
What am I missing in VBA?
It looks like Shell is supposed to return an integer. Have you tried this instead?
dim returnValue as Integer
returnValue = Shell("cmd /c move """ & logPathSource & logFileSource & """ """ & logPathDest & logFileDest & """", vbHide)

How to execute two commands sequentially

Private Sub btnUnHide_Click(sender As Object, e As EventArgs) Handles btnUnHide.Click
Dim path As String
fdbUnHide.ShowDialog()
path = fdbUnHide.SelectedPath
RunCommandCom(path)
End Sub
Shared Sub RunCommandCom(path As String)
Dim unhide As String = "attrib -r -s -h /s /d"
Try
Shell("cmd.exe /C cd " & path)
Shell("cmd.exe /C" & unhide)
End Sub
I also tried using "&" but didn't work
Shell("cmd.exe /C cd " & path "& " & unhide)
Can anybody help me with this?
NOTE: This answer addresses the problem asked in the question, but it is certainly not the best way of un-hiding a folder and its files.
THE BEST and recommended approach is described in Ctznkane525's answer.
The problem with your current code is that you are missing a space before the ampersand (&).
This:
"cmd.exe /C cd " & path & "& " & unhide
essentially becomes:
"cmd.exe /C cd C:\your\path& attrib -r -s -h /s /d"
...making & part of the path. You need to add a space before it:
"cmd.exe /C cd " & path & " & " & unhide
Though be aware that Shell() is an outdated function from the VB6 era and shouldn't be used. When "executing commads" (or more correctly: starting processes) you should use the Process.Start() method:
Process.Start("cmd.exe", "/C cd " & path & " & " & unhide)
Here is how you unhide a folder in .net and the files
Dim t As New System.IO.FileInfo(path)
t.Attributes = t.Attributes And Not FileAttributes.Hidden
For Each fn As String in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
t = New System.IO.FileInfo(fn)
t.Attributes = t.Attributes And Not FileAttributes.Hidden
Next
The attributes are a bitwise flag. You'll want to import system.io at the top.

Excel VBA Shell command with spaces in file path

Public Sub openEntryFiles()
Dim filePath, shellCommand, agingsEntry, invenEntry As String
filePath = Range("CustomerPath").Value2 & "\files\"
agingsEntry = "agings\entry_EP.bat"
invenEntry = "inven\entry_EP.bat"
shellCommand = """%ProgramFiles(x86)%\TextPad 5\TextPad.exe"" -r -q -u """ & filePath & agingsEntry & """ -u """ & filePath & invenEntry & """"
Debug.Print shellCommand
Shell shellCommand, 0
End Sub
I am trying to write a subroutine that will run a shell command with spaces in the file path. I have done lots of research about using multiple quotes, but I still get a file not found error whenever I run the code. The debug print that is outputted to the Immediate window reads:
"%ProgramFiles(x86)%\TextPad 5\TextPad.exe" -r -q -u "\\ablsgaat002\aclwin\Clients\*****\files\agings\entry_EP.bat" -u "\\ablsgaat002\aclwin\Clients\*****\files\inven\entry_EP.bat"
Copying that string into a shell window works great, however, running it from the Shell command in VBA doesn't work. What am I doing wrong?
Use Environ function to get Special Folders
pathSpecial = Environ("ProgramFiles(x86)")
shellCommand = """" & pathSpecial & "\TextPad 5\TextPad.exe"" -r -q -u """ & filePath & agingsEntry & """ -u """ & filePath & invenEntry & """"

Excel VBA shell command to search Chrome

I have the following VBA code to open Chrome and navigate to a specific page:
Sub ExampleSub()
Dim chromePath As String
chromePath = """C:\Program Files\Google\Chrome\Application\chrome.exe"""
Shell (chromePath & " -url http:google.ca")
End Sub
What I can't find is the command to use the search engine to run a Google search for a string I pass it, like this:
Search_String = "Where to find pizza in Tibet"
Shell (chromePath & " -url " & Search_String)
or
Shell(chromePath & " -search " & Search_String)
or
Shell(chromePath & " " & Search_String)
I'd be running several searches, so the search criteria needs to be dynamic.
You are formatting your URL string incorrectly. Please consider the following solution:
Sub ExampleSub()
Dim chromePath As String
Dim search_string As String
search_string = "Where to find pizza in Tibet"
search_string = Replace(search_string, " ", "+")
chromePath = "C:\Program Files\Google\Chrome\Application\chrome.exe"
' Uncomment the following line and comment out previous for Windows 64 versions
' chromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Shell (chromePath & " -url http://google.ca/#q=" & search_string)
End Sub
If you run a search from google.com and review the resulting URL you will see that search terms are seperated by +. This is why I replace all white spaces for + and then add it to the URL. Regards,

The term 'connect-nacontroller' is not recognized as the name of a cmdlet, function, script file, or operable program

Doesn't it figure. Moments after I post this, I finally get it to work. I'll post what I did just in case anyone else has this issue in the futures. It's a big oversight for me!
Right before the username line, I added this line:
"Import-Module DataOnTap" & Environment.NewLine & _**
I'm trying to run a PowerShell script from within VB.Net 2010 code. When I run the code in PowerShell, it runs fine. When I run it from within VS2010, I get the error:
"The term 'connect-nacontroller' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."
The error occurs when it gets to the "Dim results As Collection(Of PSObject) = MyPipeline.Invoke()" line.
Here is my code (I changed the username and password and will be changing how it comes into the code once I get it to work. I also changed the name of the volume):
Protected Sub ExecuteCode_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
resultBox.Text = RunScript(powerShellCodeBox.Text)
End Sub
Private Function RunScript(ByVal scriptText As String) As String
Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
MyRunSpace.Open()
Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
Dim userName As String = "abc"
Dim password As String = "123"
Dim myscript As String = "$username = " & Chr(34) & userName & Chr(34) & Environment.NewLine & _
"$password = ConvertTo-SecureString " & Chr(34) & password & Chr(34) & " -AsPlainText -Force" & Environment.NewLine & _
"$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$password" & Environment.NewLine & _
"connect-nacontroller mydrive -credential $cred" & Environment.NewLine
MyPipeline.Commands.AddScript(myscript)
MyPipeline.Commands.Add("Out-String")
Dim results As Collection(Of PSObject) = MyPipeline.Invoke()
MyRunSpace.Close()
Dim MyStringBuilder As New StringBuilder()
For Each obj As PSObject In results
MyStringBuilder.AppendLine(obj.ToString())
Next
Return MyStringBuilder.ToString()
End Function
Right before the username line, I added this line:
"Import-Module DataOnTap" & Environment.NewLine & _**