Getting shell cmd output to Excel - vba

I have a macro in VBA (Excel 2007).
It opens an exe file with entering a HEX value as variable.
The exe gives the output (also a HEX number).
I do everything with "shell" command and the results is saved to a txt file. Then I write this to Excel.
retVal = Shell("cmd.exe /c C:\AABB\app.exe 0x5110 > C:\AABB\output.txt", vbNormalFocus)
It is complicated and time-consuming.
I would prefer getting the result directly to Excel, without an intermediate file like txt or similar.
When I use an output.xlsx as output destination, the file is created and the value is written. But I cant read it with Excel. I see the value when I open the xlsx with Notepad.
My questions are:
1) Is it possible to write the result directly to xlsx, especially a target cell e.g. A10
2) Why when I use xlsx as destination in shell command, I can't open it with Excel? It gives Error Message of "file-format or file-extension is not valid. Data might be corrupted".

I think you can't do that with shell object.
you can do it with WSHExec with the function StdOut.ReadLine().
You have to go to reference and choose "Windows Script Host object model" so you can declare a WshExec object. than see the Method yourWshExecObject.StdOut.ReadLine().
To construct WshExec :
First declare a WshShell Object and you construct it like that :
Dim WshShellObject as WshShell
Dim WshExecObject as WshExec
Set WshShellObject = New WshShell
Set WshExecObject = WshShellObject.Exec("your .exe filename").
The WshExecObject.StdOut TextStream will read everything you write in the console.
I did it with an .exe compilated with C++.
You can also use WshExecObject.StdOut.ReadAll to read all lines at once.
Hope that helps.

Related

How to run a .cmd file from VBA

I am writing a macro for a Solidworks PDM Task.
I have manage to write into the script in the Task, that it should start a specified macro. This works.
In the macro I would like to open a PcSchematic file (.pro) and the run a .cmd file, which will ask PcSchematic to convert the file into a PDF. And then close the program.
I am novice in VBA - I have found and edited this macro, which opens PcSchematic, but not the file and I don't know how to proceed.
Sub Auto_Open()
Dim x As Variant
Dim Path As String
' Set the Path variable equal to the path of your program's installation
Path = "C:\Pcselcad\Pcselcad.exe"
x = Shell(Path, vbNormalFocus)
End Sub
Right now we use a Dispatch to do the trick, with a Shell execute:
Where the commandline says: C:\Pcselcad\Pcselcad.exe "%PathToSelectedFile%" C:\ODIN\administration\Dispatch\SaveAsPDF.cmd
This method is working, but it is not closing down the PcSchematics when it is done. And I would like to start it with a task, which gives me some other benefits, this is why I want to do it with a macro.

How to call java object in VBA with classpath

We use a CMD to call a PowerShell script. In the PowerShell script, a Java program is called. Both files are in the same directory. I want this all replaced by VBA within Microsoft Access. I have found several related topics but I can't decide whether it is possible or not based on these topics. Topics like Launch jar file from VBA code
The CMD contains the following code:
SET CLASSPATH=.\yyyyy.jar
powershell .\startscript.ps1
The PowerShell script contains the following sample:
& java '-Djavax.net.ssl.trustStore="zzzz.keystore"' com.router.router.router.Router -user:... etc.
We also run the same Java program in a different setting, only with the use of one .CMD-file. This is made like:
SET USR=user
SET CLASSPATH=.\yyyyy.jar
java -Djavax.net.ssl.trustStore=zzzz.keystore com.router.router.router.Router -user:%USR% etc.
Preferably both PowerShell and CMD become obsolete and the parameters like "-user" are fed with variables from the VBA code.
Does someone have a usable link, example or code? Please advice.
What you are trying to do is to run a command via the command line. It just happens that this command runs java, as far as the VBA code is concerned it may run anything that the shell would understand.
A sample code to run a command via a shell in VBA is the following (note there are many ways and it's super easy to find these samples on internet, I'm just using the first one I found):
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = False
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C " & yourCommand
... where yourCommand is the litteral string you would run in your command prompt. Now, it's all about string concatenation in VBA. Following your sample (and adding the username directly from VBA):
user = Environ("UserName")
yourCommand = "java -Djavax.net.ssl.trustStore=zzzz.keystore com.router.router.router.Router -user:" & user
(please note that I replaced %USR% - which asks the shell to retrieve the username - with a variable user that I've defined in VBA, even though in this specific example, the function Environ is asking environment variables so it's still asking it to a shell).

Error executing batch file in excel VBA windows

I was trying to execute a batch file via standard call shell() function.
This Batch file is project specific and created automatically for each project by an external application. Main function is to normalise around 40 files having statistical data used for my project. This data is being acquired form excel. While executing manually this takes around 30 seconds for the complete process and its working just fine.
When I try to access this using call shell function in VBA, It just pop up for like 2 seconds and outputs were not generated from Batch file.
I am attaching My sample code below used for this. I am just baby-stepping in VBA Macros. Please Excuse my coding practice.
Call Shell(Range("L8") & "\DSTAT$.BAT")
I tried this also
`Dim Runcc
Runcc = Shell(Range("L8") & "\DSTAT$.BAT", 1)`
Please let me know if any further information is required to sort this out.
Try
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
With CreateObject("WScript.Shell")
.Run Range("L8") & "\DSTAT$.BAT", windowStyle, waitOnReturn
End With
I use this for converting PDFs to JPG with Irfanview on report_open in Ms-Access.
Stolen from vba WScript.Shell run .exe file with parameter

VBS Writing to Text File

I want to use VB script to write to a text file and have tried using:
My.Computer.FileSystem.WriteAllText("C:\Users\Internet\test1.txt","This is new text to be added",True)
I get error -
"Cannot use parenthesis when calling a sub".
If I remove the parenthesis, I get error -
Object required: 'My'
Have searched the help forums without luck.
I'm using windows vista. could I be missing some libraries or such ?
Any help much appreciated.
This is how you can do it using vbscript.
This is a simple script to create a text file and write to it
Dim fso, objOutFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set objOutFile = fso.CreateTextFile("Myfile.txt",True)
objOutFile.WriteLine "Hello World"
You can modify it to create and write file to any other location. For writing to an existing file you need different method.

Directing the output of a cmd line procedure to Excel

I am running a cmd command on VBA using call Shell(), but I would like to get the output of the command line to paste it to a range.
something basic like:
forfiles /P C:\Directory\ /S /D %DATE:~4,10%
this returns 99% of the time either nothing or a single string (1 file name) for me which shows the files updated today.
I am hoping to get this output string pasted into a Range. Anyone know a way to redirect outputs?
I guess I can make the cmd line write to a csv and then import but that sounds inefficient to me.
Could you redirect the output of your batch script to a file, then read those file contents into a variable inside your VBA program? Then you could just load that variable value to your range.
You could read the file contents like this:
Open "C:\batch_output.txt" for input as #1
Input #1, textValue
Close #1
Your VBA code could also delete the batch output file when finished if needed.