【问题标题】:How to recursively check all subfolders for existing Excel files and extract all VBA code如何递归检查现有 Excel 文件的所有子文件夹并提取所有 VBA 代码
【发布时间】:2014-04-24 02:01:51
【问题描述】:

我正在寻找一种将 PowerShell 脚本与 VBscript 相结合的方法,以从复杂文件夹结构中的大量 excel 文件中提取所有 VBA/win32 代码。

我需要递归检查现有 Excel 文件 (PSH) 的所有子文件夹,并将所有代码 VBA/win32/dialogs (VBS) 提取到每个 Excel 工作表的同一文件夹级别的文本文件中。

我发现 VBscript 可以从 excel 表中提取 VBA 代码,请参见下面的链接和代码。现在我想将它组合到一个 PowerShell 脚本中。

你能帮帮我吗?

http://www.pretentiousname.com/excel_extractvba/index.html

代码:

option explicit

Const vbext_ct_ClassModule = 2
Const vbext_ct_Document = 100
Const vbext_ct_MSForm = 3
Const vbext_ct_StdModule = 1

Main

Sub Main
    Dim xl
    Dim fs
    Dim WBook
    Dim VBComp
    Dim Sfx
    Dim ExportFolder

    If Wscript.Arguments.Count <> 1 Then
        MsgBox "As the only argument, give the FULL path to an XLS file to extract all the VBA   from it."
    Else

        Set xl = CreateObject("Excel.Application")
        Set fs = CreateObject("Scripting.FileSystemObject")

        xl.Visible = true

        Set WBook = xl.Workbooks.Open(Trim(wScript.Arguments(0)))

        ExportFolder = WBook.Path & "\" & fs.GetBaseName(WBook.Name)

        fs.CreateFolder(ExportFolder)

        For Each VBComp In WBook.VBProject.VBComponents
            Select Case VBComp.Type
                Case vbext_ct_ClassModule, vbext_ct_Document
                    Sfx = ".cls"
                Case vbext_ct_MSForm
                    Sfx = ".frm"
                Case vbext_ct_StdModule
                    Sfx = ".bas"
                Case Else
                    Sfx = ""
            End Select
            If Sfx <> "" Then
                On Error Resume Next
                Err.Clear
                VBComp.Export ExportFolder & "\" & VBComp.Name & Sfx
                If Err.Number <> 0 Then
                    MsgBox "Failed to export " & ExportFolder & "\" & VBComp.Name & Sfx
                 End If
                On Error Goto 0
            End If
        Next

        xl.Quit
    End If
End Sub

【问题讨论】:

    标签: excel powershell recursion vbscript extract


    【解决方案1】:

    PowerShell 中的递归就是这么简单:

    Get-ChildItem 'C:\base\folder' -Include '*.xls*' -Recurse | % {
      & cscript.exe //NoLogo 'C:\path\to\your.vbs' $_.FullName
    }
    

    但是,我建议您将 VBScript 代码转换为 PowerShell,而不是为每个文件运行 VBScript。它不需要太多努力,而且还可以提高代码的整体性能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2023-02-15
      • 1970-01-01
      相关资源
      最近更新 更多