VBA:从多个文档中删除已知密码改进代码

如何解决VBA:从多个文档中删除已知密码改进代码

我们公司的标志已更改。我们有超过 5000 个模板(.doc、.docx、.dotx、.xlsx 等) 有些文件受密码保护,有些则没有。

我之前的一位前同事创建了这些(此人不再活跃于公司

所以,我已经“创建”了一个半有效的 VBA 代码。 这部分对于所有 3 个宏都是相同的。 (仅通话更改)

Sub RemovePassword()
Dim strPath As String
Dim strFile As String
Dim doc As Document
On Error GoTo ErrHandler
     
    'Batch process to go through all files in a selected folder
     
     With Application.FileDialog(msoFileDialogFolderPicker)
         .Title = "Select a folder with Word documents"
         If .Show = False Then
             MsgBox "You didn't select a folder.",vbInformation
             Exit Sub
         End If
         strPath = .SelectedItems(1)
     End With
     If Right(strPath,1) <> "\" Then
         strPath = strPath & "\"
     End If
     Application.ScreenUpdating = False
     strFile = Dir(strPath & "*.doc")
     Do While strFile <> ""
         Set doc = Documents.Open(strPath & strFile)
         
         'Call Macro (code) to process (replace only the name)
         Call RemovePwd
                  
         strFile = Dir
         doc.Save
         doc.Close
     Loop
     Exit Sub
ErrHandler:
          MsgBox Err.Description,vbExclamation
             
 End Sub

Sub RemovePwd()

    'Remove existing Pwd
    ActiveDocument.Unprotect Password:="Password" *'not the real pw'*
        
End Sub

这个删除选定文件夹中.doc文档的密码(代码有效) 这段代码有两个问题。

  1. 当文档不受密码保护时,此宏会跳过所选文件夹中的所有文档。因此,文档保持锁定状态。 我必须找到所有未受保护的文件,手动将它们从文件夹中删除,或者也为它们添加保护。

是否可以调整代码,以便在文档没有密码时跳过该文档并继续下一个文档?

  1. 是否可以调整代码,使 Word 和/或 Excel 的所有扩展程序都发生这种情况。

另外两个宏

移除旧标志

Sub RemoveOldLogo()
Dim hdr As HeaderFooter
Dim sec As Section
Dim sh As Shape
    
    'Loop through all existing headers in document
    For Each sec In ActiveDocument.Sections
    
        For Each hdr In sec.Headers
        
            Set rng = hdr.Range
            
            For Each sh In hdr.Shapes
            
                'Delete found Logo
                sh.Delete
                
            Next sh
            
        Next hdr
        
    Next sec
    
End Sub

添加新徽标

Sub AddNewLogo()


    'Copy Logo from Master template
    ChangeFileOpenDirectory "C:\MASTER_TEMPLATE\"
    Documents.Open FileName:= _
        "C:\MASTER_TEMPLATE\MASTER_Logo.doc",_
        ConfirmConversions:=False,ReadOnly:=False,AddToRecentFiles:=False,_
        PasswordDocument:="",PasswordTemplate:="",Revert:=False,_
        WritePasswordDocument:="",WritePasswordTemplate:="",Format:= _
        wdOpenFormatAuto,XMLTransform:=""
    ActiveWindow.ActivePane.View.SeekView = wdSeekFirstPageHeader
    Selection.WholeStory
    Selection.Copy
    ActiveWindow.Close
    
    'Paste Logo
    ActiveWindow.ActivePane.View.SeekView = wdSeekFirstPageHeader
    Selection.PasteAndFormat (wdFormatOriginalFormatting)

End Sub

所有这些宏组合在一起运行以下宏

Sub RunAllMacros()
        RemovePassword
        RemoveOldLogo
        AddNewLogo
End Sub

就像我说的,除了当文件夹中的 1 个文档不受密码保护时,这些代码都可以工作,它不会将其从该文件夹中具有密码的其他文档中删除。

如果有人对如何执行此操作有更好的解决方案,也欢迎提供该信息!

我对 VBA 等不太熟悉,这些都是在网上找到的,从不同的代码中调整和组合。

谢谢

氪, 蒂埃里

解决方法

如果您尝试取消保护没有保护的文档,Word 会引发运行时错误,这是您遇到的主要问题。此外,我建议您删除 On Error GoTo ErrHandler 语句(因为最好让 VBA 运行时向您显示发生错误的确切语句)。

对取消保护例程做一个简单的更改:首先检查文档是否有保护。我建议您将文档作为参数传递,这样您就不必依赖 ActiveDocument(您需要将调用更改为 Call RemovePwd(doc)(或只是 RemovePwd doc,这意味着一样)

Sub RemovePwd(doc as Document)
    If doc.ProtectionType <> wdNoProtection Then 
    'Remove existing Pwd
        doc.Unprotect Password:="Password" *'not the real pw'*
    End If
End Sub

顺便说一下,对于 Excel,不需要此检查,您可以为未受保护的工作簿发出 unprotect,而不会出现运行时错误。


要获取所有 Word 文档,请将 Dir-命令更改为

strFile = Dir(strPath & "*.do*")

这应该会找到所有的 docdocxdocmdotx ...

,

看起来好像您正在多次循环访问这组文件。只做一次会更有效率。

您还可以在一次操作中替换标题,而无需先删除标题。您的代码实际上删除了文档每个部分中的所有三种类型的标题,但仅替换了单个部分中的单个标题。下面的更新代码仅替换单个标题。您需要检查您的文档是否包含多个标题并相应地编辑代码。

如果您在代码中添加行号,您可以使错误处理更具信息性。然后你可以使用Erl来报告错误发生在哪一行。

Sub ChangeDocumentHeaders()
         Dim strPath As String
         Dim strFile As String
         Dim doc As Document
         Dim masterLogo As Document
10       On Error GoTo ErrHandler
           
         'Batch process to go through all files in a selected folder
           
20       With Application.FileDialog(msoFileDialogFolderPicker)
30          .Title = "Select a folder with Word documents"
40          If .Show = False Then
50             MsgBox "You didn't select a folder.",vbInformation
60             Exit Sub
70          End If
80          strPath = .SelectedItems(1)
90       End With
100      If Right(strPath,1) <> "\" Then
110         strPath = strPath & "\"
120      End If
130      Set masterLogo = Documents.Open("C:\MASTER_TEMPLATE\MASTER_Logo.doc")
140      Application.ScreenUpdating = False
150      strFile = Dir(strPath & "*.do*")
160      Do While strFile <> ""
170         Set doc = Documents.Open(strPath & strFile)
               
            'Call Macro (code) to process (replace only the name)
180         RemovePassword doc
190         ReplaceHeader doc,masterLogo
                        
200         strFile = Dir
210         doc.Save
220         doc.Close
230      Loop
240      masterLogo.Close
250      Exit Sub
ErrHandler:
260      MsgBox "Error on line: " & Erl & vbCr & Err.Description,vbExclamation
                   
End Sub

Sub ReplaceHeader(Target As Document,Source As Document)
   Dim NewHeader As Range
   
   Set NewHeader = Source.Sections(1).Headers(wdHeaderFooterPrimary).Range
   
   With Target.Sections(1).Headers(wdHeaderFooterPrimary).Range
      .FormattedText = NewHeader.FormattedText
      'replacing header may leave an extra empty paragraph,so remove it
      With .Paragraphs.Last.Range
         If Len(.Text) = 1 Then .Delete
      End With
   End With
   
End Sub

Sub RemovePassword(doc As Document)
    If doc.ProtectionType <> wdNoProtection Then
    'Remove existing Pwd
        doc.Unprotect Password:="Password"
    End If
End Sub

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res