I would like to have a macro in Outlook 2010 that will run a vbscript on my local drive. Here's what I've tried.
Sub RUNvbscript()
Shell "Explorer.exe ""C:\rest of path""", 1
End Sub
That did not work, any suggestions?
You have a few options here: Shell(), the ShellExecute() API function, scripting host's WShell.Run(), etc. If you need to wait for your script to complete, however, WShell.Run() has a synchronous option, which makes it nice.
strPath = "c:\folder\myscript.vbs"
Set objShell = CreateObject("WScript.Shell")
' Run synchronously...
objShell.Run Chr(34) & strPath & Chr(34), 1, True
' Or, run asynchronously...
objShell.Run Chr(34) & strPath & Chr(34), 1, False
With the others, you'd need to use WaitForSingleObject or some other polling mechanism to determine when the script completes.
Related
I am trying to automate file upload on chrome, getting error here :method run object iwshshell3 failed" please help:
Dim Customer_rates As String
Dim WshShell As Object
Customer_rates = "D:\FX Exch. Rates\2022-Feb-24 1707\MP_customer_exchange_rates_sample.xlsx"
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "cmd.exe/c echo" & Customer_rates & "| clip", vbNormal, True
WshShell.SendKeys "^{v}"
Application.Wait DateAdd("S", 2, Now)
WshShell.SendKeys "{ENTER}"
Think about how this would appear in the console. The file path has spaces. So it will require quotes around it when you run it. Something like:
WshShell.Run "cmd.exe/c echo" & chr(34) & Customer_rates & chr(34) & "| clip", vbNormal, True
Thansk guys i did a workaround of cmd with this sub and it semms to work:
Sub StoreData()
Dim varText As String
Dim objCP As Object
varText = "D:\FX Exch. Rates\2022-Feb-24 1707\MP_customer_exchange_rates_sample.xlsx"
Set objCP = CreateObject("HtmlFile")
objCP.ParentWindow.ClipboardData.SetData "text", varText
End Sub
Try to always work with absolute paths (program and arguments).
Be aware of quotes. I preferably use chr(13)
I have write a VBA code to copy file from one directory to another; but I can't figure out why it is not working. Any ideas? I know how to do it using FileSystemObject but I will like to learn - doing it with SHELL.
Sub copy_file()
Dim dirPath As String, srcFile As String
dirPath = "E:\Download\"
srcFile = ThisWorkbook.Path & "\" & ThisWorkbook.Name
Shell ("cmd /c copy /y """ & srcFile & " " & dirPath & """")
End Sub
You're over-complicating.
You don't need to use Shell and go through the command line for this.
There's a built-in command: FileCopy
Example
This example uses the FileCopy statement to copy one file to another. For purposes of this example, assume that is a file containing some data.
Dim SourceFile, DestinationFile
SourceFile = "SRCFILE" ' Define source file name.
DestinationFile = "DESTFILE" ' Define target file name.
FileCopy SourceFile, DestinationFile ' Copy source to target.
Read the documentation for FileCopy at the source.
I'd also suggest taking a few minutes to read through all the standard VBA objects and their available methods/functions/properties/etc to get an idea of what kind of tasks have built-in functionality with VBA and/or Office.
Here is the main page of the official documentation for Office VBA.
srcFile is the same file that you are using to hold your vba code, and therefore that file is already open. In that case Windows shell copy command will not work, by design.
You can duplicate your opened source file with the ActiveWorkbook.SaveAs method.
Further reading: How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?
Further problem: your active workbook will immediately renamed, therefore you have to close it. In order to avoid having save as dialog before exit, read that tutorial: https://support.microsoft.com/en-us/help/213428/how-to-suppress-save-changes-prompt-when-you-close-a-workbook-in-excel
Shell ("cmd /c copy /y """ & srcFile & " " & dirPath & """")
Quotes issue. You should be check your path and try this code below:
Sub copy_file()
Dim dirPath As String, srcFile As String
dirPath = "E:\Download\"
srcFile = ThisWorkbook.Path & "\" & ThisWorkbook.Name
MsgBox "cmd /c copy /y " & srcFile & " " & dirPath
Shell ("cmd /c copy /y " & srcFile & " " & dirPath)
End Sub
I am trying to open an Access 2003 .mde file using Excel VBA.
So far I have tried:
Shell ("cscript "C:\User\Folder\Access Database.mde""), vbHide
Now this works perfect to open a .vbs file and the code runs to open the .mde file but does not actually open the database.
I also tried the following:
strdb = "C:\User\Folder\Access Database.mde"
Set AccessApp = CreateObject("Access.Application")
AccessApp.Visible = True
AccessApp.OpenCurrentDatabase.strdb
AccessApp.DoCmd.OpenForm "frmsysteminformation"
Set AccessApp= Nothing
I found this online but it gives me a debug error highlight the line:
Set AccessApp = CreateObject("Access.Application")
Thanks
Edit My company seems to have disabled some of the features as
CreateObject("Outlook.Application")
also doesn't work. Is there a way to run this through cscript?
Just in case anyone stumbles across this same issue I managed to work it out:
Dim sAcc
Dim sFrontEnd
Dim sSec
Dim sUser
Dim objShellDb
Dim sComTxt
'Script Configuration Variable
'*******************************************************************************
'Specify the Fullpath and filename of the msaccess executable
sAcc = "C:\Program Files\Microsoft Office\Office11\MSACCESS.EXE"
'Specify the Fullpath and filename of the database to launch
sFrontEnd = "C:\users\file location\Database to open.mde"
Set objShellDb = CreateObject("WScript.Shell")
'Build the command to launch the database
sComTxt = Chr(34) & sAcc & Chr(34) & " " & Chr(34) & sFrontEnd & Chr(34)
objShellDb.Run sComTxt 'Launch the database
End Sub
I'm simulating multi-threading with VBA, the code creates multiple vbs files and runs them. But i am not able to delete them after they are completed, it says "can not find script file" Here is my code:
' Write VBScript file to disk
sFileName = ActiveWorkbook.Path & "\Thread_" & agentNr & ".vbs"
intFileNum = FreeFile
Open sFileName For Output As intFileNum
Print #intFileNum, s
Close intFileNum
' Run VBScript file
Set wshShell = CreateObject("Wscript.Shell")
wshShell.Run """" & sFileName & """"
Kill sFileName
Set wshShell = Nothing
Any idea? Thanks
In our original code, as it's in asynchronous mode, Shell has not read the script file before you removing it.
Now I suggest a self-destruction mode.
As comments, we run .vbs again in an asynchronous mode, but the script file will be removed at the end of the vbscript, ie, inside the script itself. The deletion instructions are appended at the end of the VBScript to be created:
Sub sof20351356RunVbScript()
Dim intFileNum As Integer
Dim agentNr As Long
Dim sFileName As String, s As String
Dim wshShell
agentNr = 5
' Write VBScript file to disk
sFileName = ActiveWorkbook.Path & "\Thread_" & agentNr & ".vbs"
'
' In the file, we do our job normally,
' at the end, we kill the vbscript inside the script itself:
'
s = "MyVar = 1" & vbCrLf _
& "'... do foo bar" & vbCrLf
'
' now add the Killing order:
s = s _
& "Set fso = CreateObject(""Scripting.FileSystemObject"")" & vbCrLf _
& "fso.DeleteFile """ & sFileName & """" & vbCrLf
intFileNum = FreeFile
Open sFileName For Output As intFileNum
Print #intFileNum, s
Close intFileNum
' Run VBScript file
Set wshShell = CreateObject("Wscript.Shell")
'
' in synchronous mode:
'wshShell.Run """" & sFileName & """", 0, True
'
' in asynchronous mode:
wshShell.Run """" & sFileName & """", 0, False
'Kill sFileName
Set wshShell = Nothing
End Sub
Ref: http://msdn.microsoft.com/en-us/library/d5fk67ky(v=vs.84).aspx
As I tested so confirmed, before a script begins to run, it's read at 100% in memory by the Shell (Windows Script Interpreter), so the file itself has no more any importance when it starts executing. As a consequence, you can even add the destruction instruction at the beginning of the VBscript, before your true job.
But cmd.exe .bat file cannot be handled as this.
You're trying to delete a script file that is currently running. That's probably what is causing your problem.
How about using the wshShell.Exec method instead of Run? That way you can keep track of whether the VBScript is done running or not, and delay deleting the VBS file until it is done.
Proof-of-concept, not tested:
Dim oExec
Set oExec = wshShell.Exec("sFileName")
'Can launch more processes here...
'Now check if oExec process is done
Do While oExec.Status = 0
'oExec process not done yet...
WScript.Sleep 100
Loop
'It's done. Delete the file.
Kill sFileName
This is of course a simplistic example with only one process. You could launch more of them and store their handles (like oExec) in an array/collection/dictionary. Then periodically check all the handles in succession until they are all done running.
Im having a problem with my excel vba macro. I need it to execute a batch file which is in the same folder as the excel workbook. The code works well sometimes. I don't know whats causing the error. Here's the code:
Sub writebatch()
Sheets("code").Select
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:=ThisWorkbook.path & "\code.bat",
FileFormat:=xlTextPrinter, CreateBackup:=False
Application.DisplayAlerts = True
ThisWorkbook.Saved = True
Shell "cmd.exe /k cd " & ThisWorkbook.path & "&&code.bat"
Application.Quit
End Sub
It writes the batch file, but then doesn't execute it. Only once I got the command window to not close and it said the code.bat file could not be found. So the changedir command worked. Is it possible to run cmd.exe and run the code.bat with the relative path without having to changedir?
First of all, when you launch a CMD instance you need to enclose the entire CMD argument if you use any type of operators (&):
CMD /K "command1 & command2"
And then enclose the sub-internal arguments, like this:
CMD /K "command "path with spaces" & command"
So you need to do something like this:
Shell "cmd.exe /k ""cd " & """ & ThisWorkbook.path & """ & " && code.bat"""
Notice I've used """ to escape a quote, but I don't know the way to escape a quote in VBA.
PS: remember to also enclose the code.bat if you have spaces, but ONLY if you have spaces.
I'm pretty sure the problem is down to this line
Shell "cmd.exe /k cd " & ThisWorkbook.path & "&&code.bat"
You need a space in front of the && to separate it from the cd command and after it to separate it from the code.bat.
Shell "cmd.exe /k cd " & ThisWorkbook.path & " && code.bat"
Shell "cmd.exe /k cd /d" & ThisWorkbook.path & "&& code.bat"
here, without /d cmd will open in document folder.
by /d it will open in d drive, you may change this as per your easy.
One way to insert a quote(") into a string is by using the character code conversion function Chr(34), 34 being the ASCII value for quotes(")
I hope it will useful for you.
Dim sfilename, fileName As String
Sub Run_file_bat()
fileName = "" & ThisWorkbook.Path & "\code.bat" & ""
VBA.Shell "Explorer.exe " & fileName, vbNormalFocus
End Sub