Question

I'm looking for a way how to combine PowerShell script with VBscript to extract all VBA/win32 code from a lot of excel files in complicated folder structure.

I need to recursively check all subfolders for existing Excel files (PSH) and extract all code VBA/win32/dialogs (VBS) to text files on the same folder level for each Excel sheet.

I have found VBscript which can extract VBA code from excel sheets see link and code below. Now I'd like to combine it to one PowerShell script.

Could you please kindly help me?

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

CODE:

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
Was it helpful?

Solution

Recursion in PowerShell is as simple as this:

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

However, rather than running a VBScript for each file I would recommend translating your VBScript code to PowerShell. It doesn't require much effort, and it will also improve overall performance of your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top