How do I open this application using VBA - excel

I am trying to debug the following code :
Public Sub StartExeWithArgument()
Dim strProgramName As String
Dim strArgument As String
strArgument = ""
'Call Shell("""" & strProgramName & """ """ & strArgument & """", vbNormalFocus)
Call Shell(Application.ActiveWorkbook.Path & "\eclipse.exe ", vbReadOnly)
End Sub
This code runs when I click on a particular button in excel
However, when I run the code/ click the button, I get the following error:
Run time error 5
Invalid procedure call or argument

Related

Running Exe File from CMD using VBA Excel

I am trying to run a cmd line from VBA. The command line calls a createReport.exe which creates a final CSV output file using Inputfile.csv
This is what I run manually from Command prompt window:
cd C:\Users\user123\Desktop\MyReport_folder (hits enter)
createReport.exe
-in=C:\Users\user123\Desktop\MyReport_folder\Inputfile.csv (hits enter)
When I run manually, it takes around 45 seconds to create final CSV output file.
When I run the same thing from VBA code, the screen says "starting the query step" and it stays on for 30 seconds, closes and doesn't create the final CSV output file.
Sub RunReport()
Application.DisplayAlerts = False
Dim strProgramName As String
Dim strArgument As String
strProgramName = "C:\Users\user123\Desktop\MyReport_folder\createReport.exe"
strArgument = "-in=C:\Users\user123\Desktop\MyReport_folder\Inputfile.csv"
Call Shell("""" & strProgramName & """ """ & strArgument & """", vbMaximizedFocus)
Application.DisplayAlerts = True
End Sub
I believe you first need to do a ChDir before calling the Shell() command, something like:
ChDir "C:\Users\user123\Desktop\MyReport_folder"
Call Shell("""" & strProgramName ...

Keep PowerShell console open from a VBA .exe execution

I want to keep open the PowerShell console once the execution has finished.
Actually, after the .exe execution, the PowerShell shut down. I would like to review the outputs once the execution stops, but I can't with the current code.
Sub Button_run_st()
Dim strPName As String
Dim strA As String
strPName = Range("C14").Text
strA = "--dd=" & Application.ActiveWorkbook.Path
Call Shell("" & strPName & " " & strA & "", vbNormalNoFocus)
End Sub
Does anyone know how to do it?

VBA: SaveCopyAs Method Outputting Cannot Find File Error

I'm modifying a Gantt chart excel template I found online by Vertex42 for added functionality.
One of these modifications is a checkbox inside a sheet called "Config" that, when ticked, creates a backup of the Gantt chart whenever the document is opened.
For some reason, I cannot get this simple task to work.
I've tried using both the Form control and ActiveX control check boxes, with different error messages. As far as I can tell, the Form controls are unrecommended, so I'm using the code below in the ThisWorkbook excel object, based on what I've seen online.
Private Sub Workbook_open()
Dim backupFilename As String
Dim formattedDateTime As String
If Sheets("Config").OLEObjects("AutoBackupCheckbox").Object.Value = True Then
formattedDateTime = Format(Now, "d-MMMM-yyyy, h:mm:ss")
backupfilename = Replace(ActiveWorkbook.Name, ".xlsm", " - backup " & DateTime & ".xlsm")
ActiveWorkbook.SaveCopyAs (backupfilename)
End If
End Sub
This code is getting me the error message whenever I open the document or run the debugger,
Run-time error '1004':
Sorry, we couldn't find the <filename> - backup <day>-<month>-<year>, <hour>:<minute>:<seconds>.xlsm. Is it possible it was moved, renamed or deleted?
Any ideas?
UPDATE: After running the debugger, it's complaining on the ActiveWorkbook.SaveAs line.
UPDATE 2: Changed format of 'backupFilename' to remove the '.xlsm' in the middle.
UPDATE 3: Replaced Date with date/time without slashes, and replaced SaveAs with SaveCopyAs. Updated error message.
The argument for the SaveCopyAs call is missing the path of the file.
Replace code with
Private Sub Workbook_open()
Dim backupFilename As String
Dim formattedDate As String
Dim tempFilename As String
Dim workingPath As String
Dim i As Integer
i = 1
If Sheets("Config").OLEObjects("AutoBackupCheckbox").Object.Value = True Then
formattedDate = Format(Date, "d-MMMM-yyyy, ver " & i)
workingPath = Application.ActiveWorkbook.FullName
backupFilename = Replace(workingPath, ".xlsm", " - backup " & formattedDate & ".xlsm")
tempFilename = Dir(backupFilename)
While tempFilename <> "" ' if file already exists
i = i + 1
formattedDate = Format(Date, "d-MMMM-yyyy, ver " & i)
backupFilename = Replace(workingPath, ".xlsm", " - backup " & formattedDate & ".xlsm")
tempFilename = Dir(backupFilename)
Wend
ActiveWorkbook.SaveCopyAs (backupFilename)
End If
End Sub

ActiveWorkbook.SaveAs excel 2013 1004 error

I am getting a
Run-time error '1004' Method 'SaveAs' of object '_Workbook' failed.
The code works in excel 2010. I only get this error message in excel 2013.
The error message appears after trying to run the follow line.
ActiveWorkbook.SaveAs FolderPath & SaveName & NewSaveExt, 52
Background:
The spreadsheet is an .xls
When using the Saveas I am changing it to .xlsm
I have tried it with a .xls extension and fileformat 56 and it still falls over.
I am using code from the resources listed in the code.
I am saving the file to the same folder the workbook is in.
The orignal file name is: Financial Report as at month N.xls
The new filename is : Financial Report 1516 as at month 8.xlsm
Sub SaveNewVersion_Excel()
'PURPOSE: Save file, if already exists add a new version indicator to filename
'SOURCE: www.TheSpreadsheetGuru.com/The-Code-Vault
Dim FolderPath As String
Dim myPath As String
Dim SaveName As String
Dim SaveExt As String
Dim NewSaveExt As String
Dim VersionExt As String
Dim Saved As Boolean
Dim x As Long
TestStr = ""
Saved = False
x = 0
NewSaveExt = ".xlsm"
'Version Indicator (change to liking)
VersionExt = "_v"
'Pull info about file
On Error GoTo NotSavedYet
myPath = ActiveWorkbook.FullName
myFileName = "Financial Report " & FileFinancialYear & " as at month " & MonthNumber
FolderPath = Left(myPath, InStrRev(myPath, "\"))
SaveExt = "." & Right(myPath, Len(myPath) - InStrRev(myPath, "."))
On Error GoTo 0
'Determine Base File Name
If InStr(1, myFileName, VersionExt) > 1 Then
myArray = Split(myFileName, VersionExt)
SaveName = myArray(0)
Else
SaveName = myFileName
End If
'Test to see if file name already exists
If FileExist(FolderPath & SaveName & SaveExt) = False Then
ActiveWorkbook.SaveAs FolderPath & SaveName & NewSaveExt, 52
Exit Sub
End If
'Need a new version made
Do While Saved = False
If FileExist(FolderPath & SaveName & VersionExt & x & SaveExt) = False Then
ActiveWorkbook.SaveAs FolderPath & SaveName & VersionExt & x & NewSaveExt, 52
Saved = True
Else
x = x + 1
End If
Loop
'New version saved
MsgBox "New file version saved (version " & x & ")"
Exit Sub
'Error Handler
NotSavedYet:
MsgBox "This file has not been initially saved. " & _
"Cannot save a new version!", vbCritical, "Not Saved To Computer"
End Sub
Function FileExist(FilePath As String) As Boolean
'PURPOSE: Test to see if a file exists or not
'RESOURCE: http://www.rondebruin.nl/win/s9/win003.htm
Dim TestStr As String
'Test File Path (ie "S:\Reports\Financial Report as at...")
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
'Determine if File exists
If TestStr = "" Then
FileExist = False
Else
FileExist = True
End If
End Function
Error reproduction: I was able to reproduce the error when trying to save a workbook with a FileName that already exist.
This could happen because the code checks the existence of a file named with extension SaveExt (using Function FileExist) but then try to save it as a file named with extension NewSaveExt. If these extensions are not the same then it’s possible that the file named with extension NewSaveExt already exist raising the
Run-time error ‘1004’: Method ‘SaveAs’ of object ‘_Workbook’ failed.
However this alert:
A file ‘Financial Report as month .xlsm’ already exist in this
location. Do you want to replace it?.
Should have been displayed before the error 1004
Unfortunately I cannot test the code posted in Excel 2010, but I personally think this behavior is not exclusive of Excel 2013.
Solution: If the objective is to always save the file as xlsm (value of NewSaveExt) then the code should validate the existence of a filename with that extension.
Additional comments about the code posted:
It’s a best practice to declare all variables. These variables are not declared:
TestStr, FileFinancialYear, MonthNumber, myFileName, myArray
These lines are redundant as no need to initialize variables that have not been used as yet, so they are already holding their initialized value.
TestStr = ""; Saved = False; x = 0
Suggest to use constant instead of variables for these (see Variables & Constants)
NewSaveExt = ".xlsm"; VersionExt = "_v"
New workbooks are not detected as the error handler NotSavedYet which is supposed to be triggered when the ActiveWorkbook has not been saved before (i.e. a new workbook) never gets fired as none of the commands between the On Error statements generate an error when dealing with new workbooks (see On Error Statement). If the intention is not to save New Workbooks, as implied by the error handler NotSavedYet, then validate the Path of the ActiveWorkbook, it will be empty if the workbook has not has been saved before.
The FileFinancialYear and MonthNumber variables never get populated.
Suggest to use specific workbook properties for Path and Name instead of FullName (see Workbook Object (Excel))
About the piece referred as Determine Base File Name
a. Programming: There is no need for IF statement, just use the Split function and take the item 0. The Split function returns ”a single-element array containing the entireexpression” when the delimiter is not present in the expression” (i.e. VersionExt and myFileName respectively).
b. Practicality: This piece seems to be redundant, as it’s meant to extract from variable myFileName the filename excluding the version and extension, however there is no such information in the variable as it has been populate just few lines above as:
myFileName = "Financial Report " & FileFinancialYear & " as at month " & MonthNumber
Therefore SaveName is always equal to myFileName
The first version of the file is indexed as 0 instead of 1.
The new indexed version will not always be the last index number + 1. If any of the previous versions is deleted or moved out to another folder as this version is missing the code will assign the missing version index to the latest file saved (see Fig. 1, note that time of the version 3 is newer than versions 4 & 5). Correction of this point requires a more complex approach as such it is not included in the revised code below.
Requirements: Based on the above a revised code is written that complies with the following requirements:
The procedure resides in a standalone workbook.
Files are always saved as xlOpenXMLWorkbookMacroEnabled (Extension xlsm)
New workbooks will not be saved as new versions.
Variables FileFinancialYear and MonthNumber are hardcoded as there is no indication of how they get populated (change as required).
The first time a file is saved and it does not exist in the source folder the file will be saved without version number.
The index of the first version should be 1 (change to 0 if required).
Option Explicit
Sub Wbk_SaveNewVersion_Xlsm()
Const kExt As String = ".xlsm"
Const kVrs As String = "_v"
Dim WbkAct As Workbook
Dim iYear As Integer, bMnth As Byte, sWbkStd As String
Dim sWbkPthNme As String, bVrs As Byte
Rem Set Standard Workbook Name
iYear = 2015 'Update Financial Year as required
bMnth = 9 'Update Month as required
sWbkStd = "Financial Report " & iYear & " as at month " & Format(bMnth, "00")
Rem Validate Active Workbook
Set WbkAct = ActiveWorkbook
If WbkAct.Name = ThisWorkbook.Name Then GoTo HdeThs
If WbkAct.Path = Empty Then GoTo NewWbk
Rem Get Workbook Properties
sWbkPthNme = WbkAct.Path & "\" & sWbkStd
Rem Validate Base File Existance
If Not (Fil_FileExist(sWbkPthNme & kExt)) Then
WbkAct.SaveAs sWbkPthNme & kExt, xlOpenXMLWorkbookMacroEnabled
MsgBox "A new workbook has been created: " & _
vbLf & vbLf & Chr(34) & sWbkStd & kExt & Chr(34), _
vbApplicationModal + vbInformation, "Workbook - Save a New Version - Xlsm"
Exit Sub
End If
Rem Save a New Version
bVrs = 1
sWbkPthNme = sWbkPthNme & kVrs
Do
If Fil_FileExist(sWbkPthNme & bVrs & kExt) Then
bVrs = 1 + bVrs
Else
WbkAct.SaveAs sWbkPthNme & bVrs & kExt, xlOpenXMLWorkbookMacroEnabled
Exit Do
End If
Loop
MsgBox "Version """ & bVrs & """ of workbook: " & _
vbLf & vbLf & Chr(34) & sWbkStd & Chr(34) & " has been created.", _
vbApplicationModal + vbInformation, "Workbook - Save a New Version - Xlsm"
HdeThs:
Call Wbk_Hide(ThisWorkbook)
Exit Sub
NewWbk:
MsgBox "Active Workbook """ & WbkAct.Name & """ has not been saved as yet." & vbLf & _
"A new version cannot be saved!", _
vbApplicationModal + vbCritical, "Workbook - Save New Version - Xlsm"
End Sub
Private Function Fil_FileExist(sFullName As String) As Boolean
Dim sDir As String
Fil_FileExist = (Dir(sFullName) <> Empty)
End Function
Private Sub Wbk_Hide(Wbk As Workbook)
Dim Wnd As Window
For Each Wnd In Wbk.Windows
Wnd.Visible = False
Next
End Sub

Execute AutoIt and wait for finish

I'm needing to implement a macro that runs after autoit and finished running the program it runs the rest of the macro.
I tried the Shellandwait(), but I did not find documentation explaining about it.
I took other examples of code that forum and got this:
Sub autoit()
Dim hProcess As Long
Dim xPath As String
Dim wsh As Object
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Set wsh = CreateObject("WScript.Shell")
xPath = Application.ActiveWorkbook.Path
hProcess = wsh.Run("D:\Program Files\autoit-v3\install\AutoIt3_x64.exe " _
& xPath & "\leandro.au3", 0, True)
Workbooks.Open (xPath & "\Mudança " & Format(Date, "dd_mm_yyyy") & ".csv")
End Sub
When I run it returns me this error:
"Run-time error '-2147024894 (80070002)': Method 'Run' of object 'IWshShell3' failed"
I do not know what it means and I have no idea solution.
If xPath has any spaces in it you will need to wrap the expression in quotes.
Try something like this instead:
xPath = ActiveWorkbook.Path
With CreateObject("WSCript.Shell")
.Exec "CMD /C START /WAIT ""D:\Program Files\autoit-v3\install\AutoIt3_x64.exe"" """ & xPath & "\leandro.au3"""
End With
Let me share two examples of VBA code for capturing the output stream from the AutoIt script (reads from the STDOUT stream)
VBA code:
Dim sFilePath As String
Dim objShell As Object, objCmdExec
sFilePath = String(1, 34) & Application.ActiveWorkbook.path & Application.PathSeparator & "test0.au3" & String(1, 34)
Set objShell = CreateObject("WScript.Shell")
Set objCmdExec = objShell.exec("""C:\Program Files (x86)\AutoIt3\AutoIt3.exe"" " & sFilePath)
MsgBox (objCmdExec.StdOut.ReadAll)
This is the AutoIt script for the first test (test0.au3):
Global $iPID = Run("notepad.exe", "", #SW_SHOWMAXIMIZED)
WinWait("[CLASS:Notepad]", "", 10)
Sleep(2000)
Send("Hello")
Sleep(1000)
ProcessClose($iPID)
ConsoleWrite("Done" & #CRLF)
Another option i'm finding useful is this vba class:
VBA Run Application - Capture Output. Author: dmaruca. Last updated 2012
Here an example:
Dim sFilePath As String
sFilePath = ThisWorkbook.path & Application.PathSeparator & "test.au3"
Dim RunApp As New CRunApp
RunApp.Command = "C:\Program Files (x86)\AutoIt3\AutoIt3.exe"
RunApp.AddParamater sFilePath
RunApp.AddParamater "Buenos días"
MsgBox RunApp.RunAppWait_CaptureOutput()
And the script for testing (test.au3):
MsgBox(4096, 'AutoIt MsgBox', $CmdLine[1])
ConsoleWrite($CmdLine[1] & #CRLF & "From: " & #ScriptName)

Resources