使用 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 專案物件模型的存取」選項。