VBA中关于WORD的基本应用 比如批量改页眉页脚,从文件名取数字作为页眉等等。

VBA中关于WORD的基本应用
比如批量改页眉页脚,从文件名取数字作为页眉等等。

以下是代码,直接在Word的VBA编辑器里粘贴上去就OK了。

Sub 批量转PDF()
Dim i As Variant
Dim t As Variant
Dim str As String, n As Long, fd, Nam As String
On Error GoTo err '如果程序执行错误 跳转执行Err
Set fd = Application.FileDialog(msoFileDialogFolderPicker) '允许用户选择一个文件夹
With fd
.Title = “选择目标文件夹”
If .Show = -1 Then t = .SelectedItems(1) Else Exit Sub
End With
str = Dir(t & “*.doc*”)
While Len(str) > 0
n = n + 1
Documents.Open FileName:=t & IIf(Right(t, 1) = “”, “”, “”) & str
Nam = CreateObject(“Scripting.FileSystemObject”).getextensionname(str)
ActiveDocument.ExportAsFixedFormat OutputFileName:=(t & IIf(Right(t, 1) = “”, “”, “”) & Replace(str, Nam, “pdf”)), _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True
ActiveDocument.Close False
str = Dir()
Wend
Set fd = Nothing
MsgBox (“已完成全部转换”)
err:
End Sub
Sub 文档保护()
Dim myDialog As FileDialog
Dim oFile As Variant
Dim oDoc As Document
Dim myResult As VbMsgBoxResult
Dim myPassWord As String
On Error Resume Next
myPassWord = “xyz” '此处双引号内设置自己的文档保护密码
'定义一个文件夹选取对话框
Set myDialog = Application.FileDialog(msoFileDialogFilePicker)
With myDialog
.Filters.Clear '清除所有文件筛选器中的项目
.Filters.Add “所有 WORD 文件”, “.doc", 1 '增加筛选器的项目为所有WORD文件
.AllowMultiSelect = True '允许多项选择
If .Show <> -1 Then Exit Sub
myResult = MsgBox(“选择是将进行对所选文件的设置文档保护,选择否将解除文档保护!”, vbYesNo)
For Each oFile In .SelectedItems '在所有选取项目中循环
Set oDoc = Documents.Open(FileName:=oFile, Visible:=False)
With oDoc
If myResult = vbYes Then '如果选择了进行文档保护
'如果该文档未经过保护则使用保护窗体(文档)功能
If .ProtectionType = wdNoProtection Then .Protect Type:=wdAllowOnlyComments, Password:=myPassWord
Else '如果选择了取消文档保护
'如果文档已使用了保护文档的功能,则解除文档保护
If .ProtectionType <> wdNoProtection Then .Unprotect myPassWord
End If

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值