Delete VBA code from all workbooks in a folder

后端 未结 1 1394
谎友^
谎友^ 2021-01-14 16:12

I am attempting to construct code to remotely loop through a folder with .xls files and delete the macros contained within. So far I have the individual components working,

相关标签:
1条回答
  • 2021-01-14 16:56

    Like I mentioned in my comments, you do not need to add a reference to Microsoft Visual Basic for Application Extensibility 5.3 to delete the code from the files. Consider this small exercise.

    1). Create an Excel file

    2). Paste this code in a module

    Sub Sample1()
        MsgBox "A"
    End Sub
    

    3). Save the above file as C:\Sample.xls

    4). Close the file

    5). Open a new excel file and paste this code in a module

    Option Explicit
    
    '~~> Trust Access To Visual Basics Project must be enabled.
    Sub Sample2()
        Dim wb As Workbook
        Dim i As Long
    
        '~~> Replace this with the relevant file
        '~~> We can open the files in a loop as well
        Set wb = Workbooks.Open("C:\Sample.xls")
    
        On Error Resume Next
        With wb.VBProject
            '~~> Remove the components
            For i = .VBComponents.Count To 1 Step -1
                .VBComponents.Remove .VBComponents(i)
            Next i
            '~~> Remove the code lines
            For i = .VBComponents.Count To 1 Step -1
                .VBComponents(i).CodeModule.DeleteLines _
                1, .VBComponents(i).CodeModule.CountOfLines
            Next i
        End With
        On Error GoTo 0
    End Sub
    

    6) Ensure that "Trust Access To Visual Basics Project" is enabled

    7) Run the Sample2()

    You will see that the code in Sample.xls is deleted and we haven't even set the reference to Microsoft Visual Basic for Application Extensibility 5.3.

    0 讨论(0)
提交回复
热议问题