【问题标题】:Run VBA code for multiple Excel files in R在 R 中为多个 Excel 文件运行 VBA 代码
【发布时间】:2017-05-04 10:36:26
【问题描述】:

看过这些主题

我能够复制这个过程。现在我想将它应用于位于我的工作目录中的各种 Excel 文件。

我认为为了能够从 R 运行 VBA 代码,目标文件应该包含宏。但是,我根本无法在每个 Excel 文件中保存 .bas 文件(其中包含 VBA 代码行)以便通过 R 自动运行它。我该怎么做?

谢谢。

更新

different topic 中遇到以下 vb 脚本:

Const sRootFolder = "C:\Billing\Import"
Const sExportedModule = "C:\Test\Module1.bas"
Const sMacroName = "MACRO"

Dim oFSO, oFDR, oFile ' File and Folder variables
Dim oExcel, oWB ' Excel variables (Application and Workbook)

Start    
'------------------------------
Sub Start()
    Initialize
    ProcessFilesInFolder sRootFolder
    Finish
End Sub
'------------------------------
Sub ProcessFilesInFolder(sFolder)
    ' Process the files in this folder
    For Each oFile In oFSO.GetFolder(sFolder).Files
        If IsExcelFile(oFile) Then ProcessExcelFile oFile.Path
    Next
    ' Recurse all sub-folders from this folder
    For Each oFDR In oFSO.GetFolder(sFolder).SubFolders
        ProcessFilesInFolder oFDR.Path
    Next
End Sub
'------------------------------
Sub Initialize()
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oExcel = CreateObject("Excel.Application")
End Sub
'------------------------------
Sub Finish()
    oExcel.Quit
    Set oExcel = Nothing
    Set oFSO = Nothing
End Sub
'------------------------------
Function IsExcelFile(oFile)
    IsExcelFile = (InStr(1, oFSO.GetExtensionName(oFile), "xls", vbTextCompare) > 0) And (Left(oFile.Name, 1) <> "~")
End Function
'------------------------------
Sub ProcessExcelFile(sFileName)
    On Error Resume Next
    wscript.echo "Processing file: " & sFileName ' Comment this unless using cscript in command prompt
    Set oWB = oExcel.Workbooks.Open(sFileName)
    oWB.VBProject.VBComponents.Import sExportedModule
    oExcel.Run sMacroName
    oWB.Close
    Set oWB = Nothing
End Sub
'------------------------------

但它没有执行宏...

【问题讨论】:

    标签: r vba excel


    【解决方案1】:

    R 执行此特定任务的代码如下:

    shell(shQuote(normalizePath("C:/Documents/VBS.vbs")), "cscript", flag = "//nologo")
    

    VB脚本可以在this话题中找到。

    【讨论】:

      猜你喜欢
      • 2023-01-25
      • 2022-01-18
      • 2014-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      相关资源
      最近更新 更多