|
- Sub 批量设置WORD文档密码()
- '
- ' 批量设置WORD文档密码(WORD版)
- ' 1.加密表确保A列为姓名(WORD文档名,不得重名),B列为密码
- ' 2.姓名和密码前后有空格会被删除,中间空格不会被删除
- ' 3.WORD文档和EXCEL加密表在同一目录下
- '
- Dim FileName$, PassWord$, Count%, i%
- Dim xlApp, xlwb As Object
- Dim Dict As Object, Key$, Msg$
- Dim myDoc As Document, File As Variant
- Const PWLen As Byte = 6 ' 密码长度(可根据实际修改)
- With Application.FileDialog(msoFileDialogFilePicker)
- .Filters.Clear
- .Filters.Add "WORD文档", "*.doc; *.docx", 1
- .AllowMultiSelect = True
- If .Show <> -1 Then End
- FileName = .SelectedItems(1)
- FileName = Left(FileName, InStrRev(FileName, ""))
- FileName = FileName & "加密.xlsm" ' 可根据实际修改加密文件名:加密.xlsm
- 'Debug.Print FileName
- If Len(Dir(FileName)) = 0 Then MsgBox FileName & " 文件不存在!": End
- Set Dict = CreateObject("Scripting.Dictionary")
- Set xlApp = CreateObject("Excel.Application")
- 'xlApp.Visible = True
- Set xlwb = xlApp.Workbooks.Open(FileName, ReadOnly:=True)
- With xlwb.WorkSheets("Sheet1") ' 可根据实际修改密码工作表名:Sheet1
- Count = .Cells(.Rows.Count, 1).End(-4162).Row
- For i = 2 To Count ' 无标题行:2改成1
- Key = Trim(.Cells(i, 1).Value) ' 第1列为姓名(文件名):注意绝对不能有重名!
- Dict(Key) = Right(Trim(.Cells(i, 2).Value), PWLen) ' 第2列为身份证号码(位置可修改)
- 'Debug.Print Key, Dict(Key)
- Next i
- End With
- xlwb.Close False
- xlApp.Quit
- Set xlwb = Nothing
- Set xlApp = Nothing
- For Each File In .SelectedItems
- On Error GoTo Error
- Set myDoc = Documents.Open(File)
- If myDoc Is Nothing Then
- MsgBox File & Msg
- Else
- Key = myDoc.Name
- Key = Trim(Left(Key, InStrRev(Key, ".") - 1))
- PassWord = Dict(Key)
- 'Debug.Print Key, PassWord
- If Len(PassWord) <> PWLen Then
- MsgBox "未找到" & Key & " 或 密码不规范!"
- Else
- With myDoc
- .ReadOnlyRecommended = False
- .PassWord = PassWord
- .Close True
- End With
- Set myDoc = Nothing
- End If
- End If
- Next File
- End With
- Set Dict = Nothing
- MsgBox "已完成批量加密!"
- End
- Error:
- 'Debug.Print Err.Number
- Select Case Err.Number
- Case 4198
- Msg = " 已加密并跳过!"
- Case 6295
- Msg = " 格式有问题!"
- Case 6301
- Msg = " 已打开(关闭后才能加密)!" ' 因为无法确定如有修改是否应该保存
- Case Else
- Msg = " 打开错误!"
- End Select
- On Error GoTo 0: Err.Clear
- Resume Next
- End Sub
复制代码 |
评分
-
1
查看全部评分
-
|