|
楼主 |
发表于 2024-3-31 08:18
|
显示全部楼层
Sub RemoveMacrosFromSelectedFolder()
Dim folderPath As String
Dim fileName As String
Dim wb As Workbook
Dim ws As Worksheet
Dim vbaProj As VBAProject
Dim vbaComp As VBAComponent
' 使用文件夹选择对话框让用户选择一个文件夹
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then ' 用户按下了确定按钮
folderPath = .SelectedItems(1) & "\"
Else
MsgBox "未选择文件夹。", vbExclamation
Exit Sub
End If
End With
' 检查文件夹路径是否正确
If Dir(folderPath, vbDirectory) = "" Then
MsgBox "指定的文件夹不存在,请检查路径。", vbExclamation
Exit Sub
End If
' 获取文件夹内的第一个Excel文件
fileName = Dir(folderPath & "*.xls*")
' 循环遍历文件夹内的所有Excel文件
Do While fileName <> ""
' 打开工作簿不可见
Set wb = Workbooks.Open(folderPath & fileName, ReadOnly:=True)
' 尝试移除工作簿中的宏
On Error Resume Next ' 忽略错误,继续执行下一条语句
Set vbaProj = wb.VBProject
For Each vbaComp In vbaProj.VBComponents
vbaComp.CodeModule.DeleteLines 1, vbaComp.CodeModule.CountOfLines
Next vbaComp
On Error GoTo 0 ' 恢复默认的错误处理
' 保存并关闭工作簿
wb.Close SaveChanges:=False
' 获取下一个文件名
fileName = Dir()
Loop
' 完成消息提示
MsgBox "选定文件夹内所有工作簿的宏代码已被移除。", vbInformation
End Sub |
|