method run object iwshshell3 failed vba - vba

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)

Related

More efficient way to write command prompts in VBA?

My macro for Word highlights specific words from a specified list for each document in a folder. At the end of the macro, I would like to append the names of each of these files to include "_Highlight" using the command line. I am not too familiar with using the Command Prompt in VBA, so my code ended up being messy.
I am trying to replicate the following command prompt in VBA.
for %a in (“C:\path\*.docx*”) do ren “%~a” “%~Na_Highlight%~Xa”
For the actual file path, I select a folder in FileDialog and store it in a variable to be used in the command prompt, strShellFldr. I am having some trouble concatenating all pieces of the code, especially with special characters, spaces, and quotation literals.
Here is what I tried:
The code below runs just fine, however it seems quite cumbersome. Is there a more efficient way to write this?
Shell.Run "cmd.exe /c" & "for %a in" & Chr(32) & "(" & Chr(34) & strShellFldr & Chr(34) & ")" & Chr(32) & "do ren" & Chr(32) & Chr(34) & "%~a" & Chr(34) & Chr(32) & Chr(34) & "%~Na_Hilight%~Xa" & Chr(34)
Is there a native VBA function that allows you to append a file name maybe?
Thank you for your help and my apologies for posting some wretched code on here.
This piece of VBA code can loop through a list of files in a given folder as input, and add "_Highlight" at the end of the name, just before the file extension:
example:
MyFile.txt --> MyFile_Hightlight.txt
Public Sub RenameFiles(Folder As String)
Dim oFSO As Scripting.FileSystemObject
Dim oFolder As Scripting.Folder
Dim oFile As Scripting.File
Dim ext As String
Dim Name As String
On Error GoTo ERROR_TRAP
Set oFSO = New Scripting.FileSystemObject
Set oFolder = oFSO.GetFolder(Folder)
For Each oFile In oFolder.Files
ext = Split(oFile.Name, ".")(UBound(Split(oFile.Name, ".")))
Name = Left$(oFile.Path, Len(oFile.Path) - Len(ext) - 1)
oFSO.MoveFile Name & "." & ext, Name & "_Highlight" & "." & ext
Next oFile
Set oFSO = Nothing
Set oFolder = Nothing
Set oFile = Nothing
Exit Sub
ERROR_TRAP:
Debug.Print "ERROR : RenameFiles (" & oFolder.Name & ")"
End Sub
Do not forget to add Microsoft Scripting Runtime reference first in your VB Editor.

VBA Access Write to PS1 file

I am trying to use Access 2016 as a front end for a database that when a user clicks a button it generates a Powershell script and runs it.
I am currently using this:
Dim Script As String
Script = ("test" & vbCrLf & "2nd line?")
Set f = fileSysObject.OpenTextFile("C:\Users\%Username%\Documents\Access.ps1", True, True)
f.Write Script
f.Close
Then to run the script I am using:
Dim run
run = Shell("powershell ""C:\Users\%Username%\Documents\Powershell\Access.ps1""", 1)
I realise that this is probably a really bad way of doing this! So any help is greatly appreciated!
Thanks!
EDIT:
Sorry there is no question!
The problem is that it highlights an error at 'f.write Script'
Compile Error: Method or data member not found.
The format %VAR% doesn't work in VBA, you need to Environ("VAR")
That said username doesn't return a value with that method, but you can use VBA.Environ("Username") in this case:
Dim strScript, strUserName, strFile As String
Dim objFSO, objFile as Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
strScript = ("test" & vbCrLf & "2nd line?")
strUserName = VBA.Environ("Username")
strFile = "C:\Users\" & strUserName & "\Documents\Access.ps1"
Set objFile = objFSO.CreateTextFile(strFile)
objFile.WriteLine strScript
objFile.Close
Set objFSO = Nothing
Set objFile = Nothing

Run bat file from Excel using VBA

I have test.bat file contains script:
copy host_name table_name -p table_name -t "file.csv"
Normally when I click on it, it's working fine. Now, I want to run test.bat file from Excel using vba.
strPath = ws1.Range("G2").value & "\" 'Directory to folder with bat
Shell strPath & "\test.bat", vbNormalFocus
something is wrong, because I see only snapshot/clip: like something is open and close into one sec...
just resolved it:
ChDir ThisWorkbook.Path & "\folder\"
Shell ThisWorkbook.Path & "\folder\test.bat", vbNormalFocus
im not sure with VBA and shell you using, but try something like this
Dim winShell As Object: Set winShell = CreateObject("WScript.Shell")
Dim WaitOnReturn As Boolean: WaitOnReturn = False
Dim windowStyle As Integer: windowStyle = 1
'Run the desired pair of shell commands in command prompt.
Call winShell.Run("cmd /k " & command1 & " & " & command2, windowStyle, WaitOnReturn)
'Release pointer to the command prompt.
Set winShell = Nothing
just replace my commands with your command(s) and lets see if its works
edit: just for completion my commands looks like this
Dim command1 As String: command1 = "cd /d" & projectDirectoryCell.Value
Dim command2 As String: command2 = "create_sensi.bat"

Can't delete VBScript file after running it

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.

put batch file command into VBA Excel

Here is batch file code:
#echo off >summary.txt (
for %%F in (*chkpackage.log) do findstr /l %1 "%%F" nul||echo %% F:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A:N/A)
and here is the code in VBA Excel calling the batch file:
FileSet = Sheet1.Range("C13")
txtFpath = Sheet1.Range("C7").Value
FilePath = txtFpath & "\res.bat"
ChDrive "D"
RSP = Shell(Environ$("COMSPEC"), vbNormalFocus)
Application.Wait Now + TimeValue("00:00:03")
SendKeys "CD " & txtFpath & "{ENTER}", True
Application.Wait Now + TimeValue("00:00:03")
SendKeys "start " & FilePath & " " & FileSet & "{ENTER}", True
Application.Wait Now + TimeValue("00:00:03")
SendKeys "exit " & "{ENTER}", True
Application.Wait Now + TimeValue("00:00:03")
SendKeys "exit " & "{ENTER}", True
But I don't want to use a batch file. I want to change it into command to use on VBA.
So i can use only VBA and run command line instead of using VBA to call batch and command line.
Easy explanation is I want to put that command in batch file into Excel-VBA and run it by using VBA call cmd and auto input that command to cmd like that Sendkeys code.
You can add a reference to the Microsoft Scripting Runtime (Tools -> References from the VBA IDE), which provides the FileSystemObject and allows you to do the following:
Dim fso As New FileSystemObject
Dim fle As Variant
For Each fle In fso.GetFolder(txtFpath).Files
'processing here
Next
You can limit the files to a particular pattern using the Like operator:
For Each fle In fso.GetFolder(txtFpath).Files
If fle.Name Like "*chkpackage.log" Then
'processing here
End If
Next
You can use the OpenAsTextStream method to get a TextStream object, and the ReadAll method to read the file contents:
For Each fle In fso.GetFolder(txtFpath).Files
If fle.Name Like "*chkpackage.log" Then
Dim txt As TextStream, contents As String
Set txt = fle.OpenAsTextStream(ForReading)
contents = txt.ReadAll
txt.Close
'process contents of file here
End If
Next
You can use Split(contents, vbCrLf) to split the contents into an array of lines before parsing (use vbLf or vbCr if the line delimiter is Unix/Mac and not Windows).
Alternatively, you can use the ReadLine method to read the file line by line. You need to check the AtEndOfStream property to ensure that you're not trying to read past the end of the file:
'Within the For Each loop
Dim txt As TextStream, currentLine As String
Set txt = fle.OpenAsTextStream(ForReading)
Do While Not txt.AtEndOfStream
currentLine = txt.ReadLine
'process current line here
Loop
txt.Close