Pass Variable from Excel Macro to .vbs file - vba

I have an excel button with a macro. The code simply stores the path of the workbook in a vaiable names 'MyCompletePath' and then runs a .vbs file. The code is:
MyCompletePath = ActiveWorkbook.FullName
'Run VBS file
Shell "wscript C:\Users\name\Desktop\vb.vbs", vbNormalFocus
I want to pass the variable 'MyCompletePath' from the excel file to the file which is executed using the last line.
I made some searches but didn't fully understand what their solutions do. Maybe someone can tell me how to do it.
UPDATE/EDIT: I'm now having a problem with the filepath after Shell "wscript. It has spaces in the folder name. How can I get it to work with spaces in the name?
Thank you.

You can include command line arguments after the path to your VBS file. For example:
Shell "wscript C:\Users\name\Desktop\vb.vbs BlahBlahBlah", vbNormalFocus
Then inside your VBS script, you can access them using the WScript.Arguments collection. For example:
MsgBox WScript.Arguments(0)
would pop up a message box displaying "BlahBlahBlah".
For a file path, as you indicated, which might include spaces and thus would be treated as multiple arguments to the script, I would include the argument in quotes, like this:
Shell "wscript C:\Users\name\Desktop\vb.vbs ""this has multiple words""", vbNormalFocus

based on passing argument from vba to vbs
When I write that within the vba:
Sub Macro1()
MyCompletePath = "toto"
Shell "wscript D:\\vb.vbs " & MyCompletePath
End Sub
and this in vb.vbs
MsgBox("Hello " & WScript.Arguments(0))
I do get "Hello toto"

Related

How to run a .cmd file from VBA

I am writing a macro for a Solidworks PDM Task.
I have manage to write into the script in the Task, that it should start a specified macro. This works.
In the macro I would like to open a PcSchematic file (.pro) and the run a .cmd file, which will ask PcSchematic to convert the file into a PDF. And then close the program.
I am novice in VBA - I have found and edited this macro, which opens PcSchematic, but not the file and I don't know how to proceed.
Sub Auto_Open()
Dim x As Variant
Dim Path As String
' Set the Path variable equal to the path of your program's installation
Path = "C:\Pcselcad\Pcselcad.exe"
x = Shell(Path, vbNormalFocus)
End Sub
Right now we use a Dispatch to do the trick, with a Shell execute:
Where the commandline says: C:\Pcselcad\Pcselcad.exe "%PathToSelectedFile%" C:\ODIN\administration\Dispatch\SaveAsPDF.cmd
This method is working, but it is not closing down the PcSchematics when it is done. And I would like to start it with a task, which gives me some other benefits, this is why I want to do it with a macro.

VBA - Execute or Run .bat File Inside Macro

I have been attempting to automate a series of administrative events for some of the users where I work by creating scripts and macro's and so on..
These scripts and macros work great, however, I would like to make a the process even easier for the users by running a single batch file that will systematically execute the scripts and macros.
The batch file I currently have, calls all the scripts one by one, and the very last script opens one of the xlsm workbooks which contains a few macro's in it - and here is where the issue is - There are still scripts to be executed but they can only be executed once this workbook has executed all its macros.
So my initial thought was to test if the workbook is open, if it is, delay the execution of the next script by a minute or so, then test again and again... until it is closed.. Then I thought perhaps it would be easier to execute the next set of scripts (also in a batch file) from within a macro.
So, I have this code:
Sub Run_BAT()
Set obj = CreateObject("Wscript.Shell")
obj.Run Chr(34) & "X:\Test\" & "Termination Reports Scripts\" & "Execute_Terminations.bat" & Chr(34), 0, True
Set obj = Nothing
End Sub
Which gives me an error:
Permission Denied
Then there's this code:
Sub WriteAndRunBatFile()
Call Shell("X:\Test\Termination Reports Scripts\Execute_Terminations.bat")
End Sub
Which gives me the error:
Invalid procedure call
Any and every single code sample that contains the "Shell" command gives this error.
Place your path to bat file in quotes:
Call Shell("cmd /c ""S:/somebatfile.bat""", vbNormalFocus)
Or
Call Shell("cmd.exe /C /K " & "ChDir X:\Test\Termination_Reports_Scripts && Execute_Terminations.bat", vbNormalFocus)
And yes, check permissions.
My theory is you're missing a reference in your application to the Windows Script Host Object Model.
In the VBA Editor, go to Tools, References, make sure that one's ticked.
It's not ticked by default for security reasons - imagine unintended access to the command prompt in every instance of a Microsoft Office application...!
(1) Check permission of user of that X directory.
(2) Test the code by removing spaces from directory name.
Also try the following code (Please try it by removing spaces from directory name).
Sub Button1_Click()
Call Shell("CMD.EXE /C " & "X:\Test\Termination_Reports_Scripts\Execute_Terminations.bat")
End Sub

VBA - Hide Chrome window

I have a vba routine in excel that downloads something with chrome. But I'd like to stop the chrome window from opening in front of me and instead have it run in the background, keeping the focus on my excel file.
The code looks like this :
Sub dl()
Dim WebUrl As String
WebUrl = [J1]
Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)
End Sub
I've heard of shell functions (with vbMinimizedNoFocus) which I think could do the trick but I can't find anywhere the correct syntax and an example of how to apply it...
Can anyone help me ?
Thank you very much in advance !
The documentation for Shell defines vbMinimizedNoFocus as 6 and gives the syntax:
Shell "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl, vbMinimizedNoFocus ' Should be defined in the global namespace

excel vba won't execute .bat but manually executing bat works fine

Hi I have a perfectly working bat named: start.bat
containing:
start C:\Users\*user*\Documents\*path*\hidebat.vbs
and once it is manually opened it works perfectly, meaning it opens hidebat.vbs, which opens a .bat minimized which uploads files to my cloud. Hence it's verified.
I've added
pause
to the start.bat to see what it does and when I tell excel to open the start.bat it will open cmd and display the exact command as required, but it will not execute the hidebat.vbs.
I expect that there is somehow some path constraint or environment constraint when it is run from excel that prevents it to actually reach out of that limited environment.
Within excel I have tried calling the .bat in 3 different ways with:
Dim path As String
path = Application.ActiveWorkbook.path
path = path & "\"
Dim MY_FILENAME3 As String
MY_FILENAME3 = path & "start.bat"
1.
retVal = Shell(MY_FILENAME3, vbNormalFocus)
' NOTE THE BATCH FILE WILL RUN, BUT THE CODE WILL CONTINUE TO RUN.
If retVal = 0 Then
MsgBox "An Error Occured"
Close #FileNumber
End
End If
2.
PathCrnt = ActiveWorkbook.path
Call Shell(PathCrnt & "start.bat")
3.
Dim batPath As String: batPath = path
Call Shell(Environ$("COMSPEC") & " /c " & batPath & "start.bat", vbNormalFocus)
Does anybody have any clue on why it will not execute the .bat file, or what I could do to ensure it will run correctly?
Note. I think it is because it opens the default path, so I'm gonna tell it to "cd" to the actual path where the excel is saved and where the .bat files are.
Yes that was it, the path was set to some random/standard/working/current path by command, so I had to add:
Print #FileNumber, "cd " & path
to the excel macro
so that start.bat looked like:
cd *path*
start *path*\hidebat.vbs
Hope this helps future me's.

Save and open vbs script programmatically

I have searched a lot on this method but no way
I want my VB Program as once opened it gives user some messages using vbs script file
so once program is opened the vbs file saved in temp and be ran to say the message to user
i have used this code with the vbs file imported to Resources
but unfortunately it works only with one line script not script with many lines
Dim Variable As String = Environ("temp") & "Message.vbs"
If Not System.IO.File.Exists(Variable) Then
System.IO.File.WriteAllBytes(Variable, My.Resources.Message)
End If
Process.Start(Variable)
i have used this second code as well but it gives error in compilation because of Save
Dim Variable As String = Environ("temp") & "\Message.vbs"
IO.File.Delete(Variable)
My.Resources.Access.Save(Variable )
Shell("explorer" & Variable )
Please Help me with this code, i have spend a long time to get solution but nothing
Thanks in advance
I made some minor changes to your first example and created a simple vbs file. The first change is because a VB script file is a just a text file I added the resource as a text file and changed the WriteAllBytes statement to WriteAllText. Second, because WriteAllText, (and WriteAllBytes also), overwrite the file if it already exists I eliminated the If statement. You may still want that, in case you really do not want to overwrite the file. Finally, I added a backslash to the beginning of the filename to create the file in the temp folder. Otherwise you get drive:\temppath\tempMessage.vbs". This executed my simple script file just fine.
.NET code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Variable As String = Environ("temp") & "\Message.vbs"
System.IO.File.WriteAllText(Variable, My.Resources.hello)
Process.Start(Variable)
End Sub
My VBScript file:
MsgBox "Hello World", 0,"Messagebox #1"
MsgBox "My name is Fred", 0,"Messagebox #2"
MsgBox "I have to go now", 0,"Messagebox #3"