0

My VBA code runs a batch file which gives call to an executable file (C# application). This exe is used to export data from a datasource and writes it in a file created in a subfolder in current directory. When I run this code, it launches the command prompt and calls the exe, but this exe does not create a file in my subfolder. When I run this exe manually, it does the job successfully.

This is the VBA code which runs the batch file:

Call Shell("C:\Users\Administrator\Desktop\ClientApp\ExportData.exe 0", vbNormalFocus)

And, this is the code from the C# application which creates a file and writes the result to it:

File.WriteAllText(Directory.GetCurrentDirectory() + "\\temp.bat", command + columnKeys);

var process = Process.Start(Directory.GetCurrentDirectory() + "\\temp.bat");
process.WaitForExit();

The batch called by C# code exports data from a datasource, and writes it to a csv file in sub folder.

I am not able to understand where do I need to make the change - whether in VBA code or in C# code - so that the code could write to the file. How do I resolve this?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Jaqen H'ghar
  • 1,839
  • 7
  • 37
  • 66
  • 2
    Check what the current directory is when running the batch file from VBA (`Directory.GetCurrentDirectory()`, I think). I assume that it changes somehow. – ENIAC Aug 07 '20 at 06:22
  • See https://stackoverflow.com/questions/15653921/get-current-folder-path for a better way to get the correct location to write the file (assuming you mean to write it to the same folder as your C# exe) – Tim Williams Aug 07 '20 at 06:35
  • The VBA code looks to run an .exe file... If `ExportData.exe` runs, then the **VBA code does its job**. Then, is 'temp.bat` file written? If yes, **is it correctly written**? It maybe runs but it does not do what you expect. If you manually run it, does it what you need? I would firstly check how `command + columnKeys` is built... – FaneDuru Aug 07 '20 at 06:43
  • @FaneDuru, OP states _"When I run this exe manually, it does the job successfully."_ So the issue does not lie with the `batch-file` – Gerhard Aug 07 '20 at 07:11
  • 1
    Why is `cmd.exe` processing a batch file needed at all? `cmd.exe` uses the same Windows kernel function which any application written in C# can use, too. So everything coded in batch file can be coded also in C# to have the entire task done with one executable. That avoids issues like this one. C# [Process class](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process) results in using [CreateProcessW](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw) which `cmd.exe` uses also to run an executable specified in a batch file. – Mofi Aug 07 '20 at 07:12
  • Ditto why call C# when you can probably do it in VBA... – Tim Williams Aug 07 '20 at 21:06

0 Answers0