Simply call a Shell
command using the automated Rscript.exe. However first, you may need to export your query data into a format R can read such as csv or txt file. Alternatively, have R connect to database via RODBC.
In the command line call you can send parameters such as query name (for RODBC SQL statement) or csv/txt path for R to receive by concatenating the shell string with space-separated values. Then use commandArgs() list in R to receive values.
Also, double quotes are needed if path names have any space. And if you have Rscript in your environmental variable, PATH, you can use the Rscript
command directly. Otherwise, enter full path where Rscript.exe resides (usually in installation bin folder). Examples commented out:
Private Sub QueryCmdButton_Click()
DoCmd.TransferText acExportDelim, , "qryToExport", "C:\Path\To\CSV.csv"
Shell "Rscript ""C:\Path\To\R\script.R""", vbNormalFocus
' Shell "C:\Path\To\Rscript.exe ""C:\Path\To\R\script.R""", vbNormalFocus
' Shell "Rscript ""C:\Path\To\R\script.R""" & " " & qryName & " " & csvPath, vbNormalFocus
MsgBox "Successfully processed R script!", vbInformation
End Sub
Or a more sophisticated Shell
call to receive a return code for error handling:
Sub RunRscript()
Dim shell As Object
Dim path As String
Dim waitTillComplete As Boolean: waitTillComplete = True
Dim style As Integer: style = 1
Dim errorCode As Integer
DoCmd.TransferText acExportDelim, , "qryToExport", "C:\Path\To\CSV.csv"
Set shell = VBA.CreateObject("WScript.Shell")
path = "RScript ""C:\Path\To\R\script.R"""
errorCode = shell.Run(path, style, waitTillComplete)
Set shell = Nothing
End Sub