0

In my VBA code I call the bat using Call Shell(....).

I need now to get the "Echo answer" inside the batch-file in VBA.

How can I do that?

My batch-file:

@echo off
IF exist %3 (robocopy %1 %2 /e ) ELSE (echo 1)

I want to get that "1" in VBA.

d219
  • 2,707
  • 5
  • 31
  • 36
David_helo
  • 187
  • 2
  • 2
  • 12
  • Please include your code and expected return value. – QHarr Aug 10 '18 at 10:07
  • There you have. – David_helo Aug 10 '18 at 10:12
  • Did you have a look at these? https://stackoverflow.com/questions/2784367/capture-output-value-from-a-shell-command-in-vba – QHarr Aug 10 '18 at 10:33
  • @QHarr Oo That one's top upvoted answer uses a 14-line function for something I usually just do in a one-liner. And accepted answer uses a whole bunch of WinAPI stuff for it! – Erik A Aug 10 '18 at 10:58
  • @ErikvonAsmuth I know. I used the same as you in my answer here https://stackoverflow.com/a/50073239/6241235 – QHarr Aug 10 '18 at 10:59
  • Yes @QHarr. I take a look to that answer before, but mi lvl of knowledge makes me feel indifferent with that kind of solution. – David_helo Aug 10 '18 at 11:43

1 Answers1

3

You can't return answers using Call Shell. You need to use WScript.Shell, and can use the read lines from the execution object it returns.

Dim sh As Object
Set sh = CreateObject("WScript.Shell")
Dim ex As Object
Set ex = sh.Exec("C:\Path\To\File.bat")
Dim ans As String
ans = ex.StdOut.ReadAll

A shorthand, if you want to save lines:

Dim ans As String
ans = CreateObject("WScript.Shell").Exec("C:\Path\To\File.bat").StdOut.ReadAll
Erik A
  • 31,639
  • 12
  • 42
  • 67