I am trying to run shell commands from VBA and get output into a csv file. Below is the code I am using:
Dim wsh as Object
Set wsh = VBA.CreateObject("WScript.Shell")
plink_path="C:\plink.exe"
key_path="putty key path"
pass_query="select * from test"
command1 = Replace(plink_path & " hadoop#11.11.11.11 -i " & key_path & " mysql -uuser -ppass -e 'use radar;" & pass_query & "'", Chr(10), " ")
wsh.Run command1 & ">E:/anurag.csv", 0, True
But I am not able to view output file in the E drive. When I run the above command manually from a cmd prompt I do get an output in the E drive.
Two thoughts:
Try E:\anurag.csv instead of E:/anurag.csv
Use cmd to invoke plink, since cmd usually processes the redirections. Replace the wsh.Run line with:
command1 = command1 & ">E:\anurag.csv"
command1 = "cmd /c """ & command1 & """"
wsh.Run command1, 0, True
The first line completes the command you wanted to execute and the second wraps it in a cmd /c call.
If this doesn't work, try changing /c above to /c /s per this answer.
YMMV - not tested
Related
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)
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.
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 & """"
I was trying to use shell function in vb.net to run a program and then write/export the result else where , it works on win8 but not XP !! The command line prints this error
'C:\Documents' is not recognized as an internal or external command,
operable program or batch file.
Press any key to continue . . .
Dim save as String="C:\exported.txt"
Dim command As String = tempPath & "app.exe -f " & IO.Path.GetTempPath & " -o " & save & " & pause"
shell("cmd /c " & command, AppWinStyle.NormalFocus, True)
Process.Start(IO.Path.Combine(tempPath, "app.exe"), "-f """ & IO.Path.GetTempPath & """ -o """ & Save() & """ & pause")
You hace a folder in the command with a space in it (probably the documents and Settings folder). cmd.exe has no way of telling whether the space is in the file name or the end of the file name, unless you put the file name in "" - like "C:\doxuments and Settings..."
Dim command As String = tempPath & "app.exe -f \"" & IO.Path.GetTempPath & "\" -o \"" & save & "\" & pause"
(\" is intended to escape a " so that it translates to embedding a " in the string. I'm not sure what the VB syntax is.)
EDIT:
I think #Roy van der Velde below has the 'escaping correct. The final part not checked is tempPath. See my comment on the question.
i want my program to open cmd , change directory and then do the command : "copy /B file1 file2 output"
this is what i have at the moment. but all that happens is a cmd window flashes for a second but no file gets created
Dim cmd1 As String
Dim cmd2 As String
cmd1 = "cd " & FolderFromFileName(imagename)
cmd2 = "copy /B " & NameOnlyFromFullPath(imagename) & "+" & "TEMP.txt" & " " & TextBox1.Text
Shell("cmd /c" & " " & cmd1 & " " & cmd2, AppWinStyle.NormalFocus)
please help, thanks :)
Do you really need to have a command prompt appear? You could do all this without a separate process by using the system.io library. If you really need the cmd prompt you can create a process.
Dim NewProcess = New Process
' a new process is created
NewProcess.StartInfo.UseShellExecute = False
' redirect IO
' PVWCmd.StartInfo.RedirectStandardOutput = True
' PVWCmd.StartInfo.RedirectStandardError = True
' PVWCmd.StartInfo.RedirectStandardInput = True
' don't even bring up the console window
NewProcess.StartInfo.CreateNoWindow = False
' executable command line info
NewProcess.StartInfo.FileName = "cmd"
NewProcess.StartInfo.WorkingDirectory = "C:\"
' NewProcess.StartInfo.Arguments = +" > """ + "LogFile.log" + """ 2>&1"
NewProcess.Start()