【问题标题】:Executing R script from command button in Microsoft Access and passing data from Microsoft Access to R从 Microsoft Access 中的命令按钮执行 R 脚本并将数据从 Microsoft Access 传递到 R
【发布时间】:2017-02-25 20:42:44
【问题描述】:

我想向 R 发送查询并从 Microsoft Access 中的命令按钮执行 R 脚本。有没有人这样做过并且可以建议如何实现这个?

数据存储在 Microsoft Access 中,查询基于用户在 Microsoft Access 中单击的按钮。

谢谢

【问题讨论】:

    标签: sql-server r ms-access


    【解决方案1】:

    只需使用自动化的Rscript.exe 调用Shell 命令。但是首先,您可能需要将查询数据导出为 R 可以读取的格式,例如 csv 或 txt 文件。或者,让 R 通过 RODBC 连接到数据库。

    在命令行调用中,您可以发送参数,例如查询名称(用于 RODBC SQL 语句)或 csv/txt 路径以供 R 接收,方法是将 shell 字符串与空格分隔的值连接起来。然后在 R 中使用commandArgs() 列表来接收值。

    此外,如果路径名有空格,则需要双引号。如果你的环境变量中有RscriptPATH,你可以直接使用Rscript 命令。否则,输入 Rscript.exe 所在的完整路径(通常在安装 bin 文件夹中)。注释掉的例子:

    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
    

    或者更复杂的Shell 调用来接收错误处理的返回码:

    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
    

    【讨论】:

    • 抱歉之前烦人的 cmets。我找不到有关此方法的任何好的文档,但您似乎明白这一点。我能够让您的代码的“简单”版本在一个例外情况下工作,请参阅。 stackoverflow.com/questions/40538004/… 另外,我尝试将路径替换为您的代码的“花哨”版本,但每次都会收到错误消息,不知道为什么?感谢您的帮助
    【解决方案2】:

    您可以使用 VBA 从 Microsoft Access 运行 R 代码,请参阅 https://www.r-bloggers.com/a-million-ways-to-connect-r-and-excel/

    要为您的 VBA 代码创建命令按钮,请参阅 https://social.technet.microsoft.com/Forums/office/en-US/d3640d72-e91f-4d86-a52e-6d3a66888bf8/how-to-create-a-button-in-access-2010-that-runs-vba-code?forum=officesetupdeployprevious

    在您的 R 代码中,您可以使用 ODBC 访问 Microsoft Access 数据库,请参阅http://rprogramming.net/connect-to-ms-access-in-r/

    如果您对 64 位 Windows 和 R 有疑问,请参阅 How to connect R with Access database in 64-bit Window?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多