I'm trying to write a code that would create and execute two batch scripts, one after another. The 1st makes a given number of copies of my pdf file (makecopies.bat) and the 2nd one changes the names of the copies according to a list of names. Thus, it is crucial that the execution of the 1st goes to completion before the 2nd one runs. That is why I refrain from using Call Shell("cmd.exe /k cd " & CurDir & " && makecopies.bat", vbHide) - I tried it and it would result in overlapping execution of scripts.
Instead, I tried to make it work with WScript.Shell, because that method allows setting waitOnReturn value. However, the problem is as follows (I need to execute two scripts, I use one as an example):
the part below works fine on my own laptop and when I try to run the code on my company computer (the one I intend to use the code at), it gives "Run time error -2147024894(80070002) Automation error The file cannot be found"
Dim wsh As WshShell
Set wsh = New WshShell
Dim makecopies As String
Dim script_makecopies As Long
Open CurDir & "\makecopies.bat" For Output As #FileNumber
Print #FileNumber, Range("B2").Value
Close #FileNumber
makecopies = CurDir & "\makecopies.bat"
script_makecopies = wsh.Run(makecopies, windowStyle:=0, waitOnReturn:=True)
I tried to change my code in order to overcome the problem - and it kind of worked, creating another problem in turn :D I replaced the last line with wsh.Run "cmd.exe /k makecopies", 0, True. This gets the job done, however at this point Excel stops responding and the rest of code (i.e. the second batch file) is not executed. I noticed that when removing /k Excel works fine and the code that follows this line is executed, but the batch (makecopies.bat) itself is not.
Does anyone have any idea how can I make it work? (Thank you in advance!)
Related
I am having an issue trying to run a complex HTTP Request through a powershell command from a VBA function.
VBA Code Below: The powershell script runs fine from inside powershell
Public Function PS_GetOutput(id As String) As String
'Setup the powershell command properly
psCommand = "powershell -command " & "C:\Users\promney\temp1\curlCommand.ps1 " & id
'Execute the command
CreateObject("WScript.Shell").Run psCommand, 3, True
'Get an instance of the clipboard to capture the save value
End Function
The PS1 file should grab the html and put a string on the clipboard. Instead, the PS window opens as a blue field, then it and excel crash completely and immediately. What am I doing wrong here?
Note: I would include the PS script but that is a lot of possibly sensitive info to scrub and I'm pretty sure the issue is in the VBA, since it works fine unless called from excel.
I've written a macro which sums numbers, grouping by year and by month based on our projection model.
It runs from start to end when stepping through with F8.
It stops immediately in standard execution with F5.
The first trouble is
Runtime error 91
in
issmIndex = Range("A1:Z1").Find("ck.IssMon").Column 'issmIndex an integer
Originally I tried Application.WorksheetFunction.Match(...) but had the same problem: runs in debug, but not in execute (Error 1004 instead).
I considered it could have been an Excel version issue (the Match function has a different name in the Italian version). I switched to a more neutral Find, but still no luck.
When you have an error with a line that is a combination of several commands, try breaking it down into the individual steps.
For example, this works:
Sub findDemo()
Const toFind = "blah"
Dim rg As Range, f As Range
Set rg = Range("A2:C5")
Set f = rg.Find(toFind)
If f Is Nothing Then
Stop 'not found
Else
Debug.Print "found in column #" & f.Column
End If
End Sub
Also see the example in the documentation for Range.Find().
Welcome to SO. Sometimes Excel reads code faster than executing, so when reading a command there is a previous one not finished. IT's weird but it happens a lot if your code does a lot of stuff and calculus.
Besides, when debugging, every command line is executed before reading next one, so you cannot detect this just debugging.
So if your code runs perfect when debugged but errors if executed as normal, try to add the command DoEvents right before the problematic line. Something like this:
' your previous code
'
'
'
Doevents
issmIndex = Range("A1:Z1").Find("ck.IssMon").Column 'issmIndex an integer
'
'rest of your code
This commands forces Excel to make sure everything has been executed before reading. It's kind of like a checkpoint, something like make sure you've done everything before going to next line.
DoEvents
function
I have an Excel macro that I would like to run automatically when the file is opened. The only way I have gotten this to work is by adding a msgbox before calling to my subroutines. However, this requires me to click OK or close the box for the macros to run. I have tried using a timed msgbox sub, but this also does not work.
For some reason, the msgbox pops up before Excel is fully opened, at which point the macro gets stuck here (code for this is below). From here, I tried waiting for the file itself to be opened until it is in write-mode (Workbook.ReadOnly = false). This also did not work.
Public Sub msgBoxTimer()
Const timeout = 2
Dim objShell As Object
Set objShell = CreateObject("WScript.Shell")
objShell.Popup "Measurement will begin shortly", timeout
End Sub
Private Sub Workbook_Open()
Call msgBoxTimer
Call init ' initiate device
Call updateIndex ' collect & record measurements
End Sub
I get from your comment that you are probably running other shell commands in init and updateIndex.
What needs to be clear is that when you execute a Shell command via a Shell object in VBA, the default behavior is not to wait for the shell command to complete before running the next line of codes.
If you want Excel to wait for the Shell command to be completed before continuing, you can have a look at the answers to this question.
That being say, if you want Excel to be fully open before running any shell commands, you can use a MsgBox like you originally intended, but it has to be VBA's MsgBox that you would simply call like this:
MsgBox "Measurement will begin shortly"
The VBA thread will wait for the "OK" button to be pressed before continuing the execution.
So I'm fairly new to VBA, using it within some spreadsheets so forgive me if this is a super obvious fix, I'm sure it is but have spent hours on with with no success.
The following piece of code will lie inside of an if statement - not sure if thats worth mentioning or not.
I want to simply move, and rename files from one location to the other
It needs to utilize cmd.exe, and use the 'move' argument - the source path and source destinations will be changeable depending on the pc - so it will need to use the '%temp% - as the initial file will be stored in this folder, and %userprofile% for the destination path.
Here is the code so far - I think the issue is just to do with the formatting -
Sub movefile ()
Dim Origpath As String
Dim NewPath As String
OrigPath="%temp%\newfile.txt"
NewPath="%userprofile%`Documents\newfile.vbs"
<<next code inside of an if statement>>
moveFile="C:\windows\system32\cmd.exe /C move " & OrigPath & " " & NewPath
End Sub
Maybe the " and & arent placed correctly? But the code works fine up until the line 'movefile...'
Probably a super easy way of doing it - help please!!
Try using Name:
name OrigPath as NewPath
Alternatively you can use use fdo movefile, as explained in this answer.
I have a Fortran routine which reads the data from a file, processes the data, and records the results in few *.csv files. It has perfectly worked for years.
Now I made a VBA Excel Macro which prepares the data files, calls the Fortran routine
TemporFile = Directory & "\" & "VTFeV4.exe"
Call Shell(TemporFile, 0)
, and forms an Excel workbook using the *.csv files generated by the Fortran routine VTFeV4.exe.
The problem is, it doesn't work consistently. Sometimes, the resulting files do not appear, the VBA Macro indeed canot find the file, and interrups. The Windows' Start Task Manager shows that the EXE file is still running.
(Please note, "Directory" is the correct Path).
I found that if to run the Macro stepwisely (F8), it works better. So I added time delay
Dim PauseTime, Start, Finish, TotalTime
PauseTime = pt
Start = Timer
Do While Timer < Start + PauseTime
DoEvents
Loop
which worked well with pt=10 until TODAY (02/22/17) when it stopped working at all even when pt=20s though the EXE file works well and fast (apparently much quicker than 10s, less to say!).
I also tried
ABC = Shell(Directory & "\NewVTF1.exe", 1)
with same result.
What is the problem with Shell? Please help!