使用 VBA 从文件夹中的工作簿删除所有宏在本节中,我将演示如何使用 VBA 宏高效地从指定文件夹中的所有工作簿中删除宏。

注意: 在使用 VBA 宏删除宏之前,您需要: 导航到 文件 > 选项 > 信任中心 > 信任中心设置 > 宏设置,然后选择“信任对 VBA 工程对象模型的访问”选项。 确保在执行此 VBA 时指定文件夹中的所有工作簿都已关闭。运行时如果有打开的工作簿可能会导致错误。步骤 1:创建新模块

按 Alt + F11 打开 Visual Basic for Applications (VBA) 编辑器。 单击 插入 > 模块 以创建一个新模块。 步骤 2:将 VBA 代码复制到模块窗口

复制以下 VBA 代码并将其粘贴到打开的 模块 窗口中。

Sub RemoveMacrosFromWorkbooks()

' Update by ExtendOffice

Dim wb As Workbook

Dim FolderPath As String

Dim filename As String

Dim VBComp As Object

Dim VBProj As Object

With Application.FileDialog(msoFileDialogFolderPicker)

.title = "Select a folder"

.Show

If .SelectedItems.Count = 0 Then

MsgBox "No folder selected. The procedure will exit.", vbExclamation

Exit Sub

End If

FolderPath = .SelectedItems(1)

End With

If Right(FolderPath, 1) <> "\" Then FolderPath = FolderPath + "\"

filename = Dir(FolderPath & "*.xls*")

Application.ScreenUpdating = False

Application.DisplayAlerts = False

On Error Resume Next

Do While filename <> ""

Set wb = Workbooks.Open(FolderPath & filename)

If wb.HasVBProject Then

Set VBProj = wb.VBProject

For Each VBComp In VBProj.VBComponents

VBProj.VBComponents.Remove VBComp

Next VBComp

End If

wb.Close SaveChanges:=True

filename = Dir

Loop

Application.ScreenUpdating = True

Application.DisplayAlerts = True

MsgBox "Macros removal completed!", vbInformation

End Sub步骤 3:运行 VBA 代码

在 模块 窗口中,按 F5 或单击 按钮以执行粘贴的代码。 在出现的“选择文件夹”窗口中,选择包含要删除宏的工作簿的文件夹,然后单击 确定。 结果

宏处理完所选文件夹中的所有 Excel 文件并删除其中的宏后,您将看到一个“宏删除完成!”的消息框。

注意:

此方法不会删除用户窗体、Excel 5/95 对话框工作表及类似元素。如果您希望消除这些内容,请参考下一个方法。 激活“信任对 VBA 工程对象模型的访问”选项可能会带来安全风险。建议仅在运行此代码时启用该选项。确保代码执行完成后取消选择“信任对 VBA 工程对象模型的访问”选项。