4

Let's say I want to run a VBS script from R, and I want to pass a value from R to that script.

For example, in a simple file called 'Msg_Script.vbs', I have the code:

Dim Msg_Text

Msg_Text = "[Insert Text Here]"

MsgBox("Hello " & Msg_Text)

How do I run this script using R, while editing the parameters and/or variables in R? In the above script for instance, how would I edit the value of the Msg_Text variable?

2 Answers 2

5

Another way would be to pass the value as an argument to the VBScript

You'd write the VBS as follows:

Dim Msg_Text
Msg_Text = WScript.Arguments(0)
MsgBox("Hello " & Msg_Text)

And then you'd create a system command in R like this:

system_command <- paste("WScript",
                        '"Msg_Script.vbs"',
                        '"World"',
                        sep = " ")
system(command = system_command,
       wait = TRUE)

This approach matches the arguments by position. If you wanted, you could use named arguments instead. This way, your VBS would look like this:

Dim Msg_Text
Msg_Text = WScript.Arguments.Named.Item("Msg_Text")
MsgBox("Hello " & Msg_Text)

And then you'd create a system command in R like this:

system_command <- paste("WScript",
                        '"Msg_Script.vbs"',
                        '/Msg_Text:"World"',
                        sep = " ")
system(command = system_command,
       wait = TRUE)
Sign up to request clarification or add additional context in comments.

2 Comments

How do you choose in what excel file to run the vbs?
@AlvaroMorales this is referring to standalone VBS on Windows not VBA that is used in Office applications
3

Here's a somewhat-hackish solution:

Read the lines from the vbs script into R (using readLines()):

vbs_lines <- readLines(con = "Msg_Script.vbs")

Edit the lines in R by finding and replacing specific text:

updated_vbs_lines <- gsub(x = vbs_lines,
                          pattern = "[Insert Text Here]",
                          replacement = "World",
                          fixed = TRUE)

Create a new VBS script using the updated lines:

writeLines(text = updated_vbs_lines,
           con = "Temporary VBS Script.vbs")

Run the script using a system command:

full_temp_script_path <- normalizePath("Temporary VBS Script.vbs")
system_command <- paste0("WScript ", '"', full_temp_script_path, '"')

system(command = system_command,
       wait = TRUE)

Delete the new script after you've run it:

file.remove("Temporary VBS Script.vbs")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.