我有一个 VBA 宏,它获取一个 Word 文档并将其逐页拆分为单独的 Word 文档。它主要基于此:http://www.vbaexpress.com/kb/getarticle.php?kb_id=727
文档的每一页都有一个以“职位名称:”开头的段落,后跟职位名称。我修改了宏以从该行中提取职位名称并将其复制到文件名中。它确实做到了,但文件名中的职位名称后面出现了一个问号。
我认为这是一个非打印字符,所以我尝试修剪并尝试替换 ^p、^m 和其他不可见字符。那行不通。如果我通过 MsgBox 运行 jobTitle 或 strNewFileName,问号不会出现。
Option Explicit
Sub SplitIntoPages()
Dim docMultiple As Document
Dim docSingle As Document
Dim rngPage As Range
Dim iCurrentPage As Integer
Dim iPageCount As Integer
Dim strNewFileName As String
Dim rngForFindSelect As Range
Dim jobTitle As String
Dim jobTitleForFilename As String
Application.ScreenUpdating = False
Set docMultiple = ActiveDocument 'Work on the active document (the one currently containing the Selection)
Set rngPage = docMultiple.Range 'instantiate the range object
iCurrentPage = 1
iPageCount = 5 'limiting to 5 pages for testing
'docMultiple.Content.ComputeStatistics(wdStatisticPages) 'get the document's page count
Do Until iCurrentPage > iPageCount
If iCurrentPage = iPageCount Then
rngPage.End = ActiveDocument.Range.End 'last page (there won't be a next page)
Else
'Find the beginning of the next page
'Must use the Selection object. The Range.Goto method will not work on a page
Selection.GoTo wdGoToPage, wdGoToAbsolute, iCurrentPage + 1 'Set the end of the range to the point between the pages
rngPage.End = Selection.Start
End If
rngPage.Copy 'copy the page into the Windows clipboard
Set docSingle = Documents.Add 'create a new document
docSingle.Range.Paste 'paste the clipboard contents to the new document
'remove any manual page break to prevent a second blank
docSingle.Range.Find.Execute FindText:="^b", ReplaceWith:="^p"
Set rngForFindSelect = docSingle.Range
With rngForFindSelect.Find
.Execute FindText:="Job Title"
If .Found = True Then
.Parent.Expand Unit:=wdSentence
jobTitle = .Parent.Text
End If
End With
jobTitle = Replace(jobTitle, "Job Title: ", "")
jobTitle = Trim(jobTitle)
'build a new sequentially-numbered file name based on the original multi-paged file name and path
strNewFileName = Replace(docMultiple.FullName, ".docm", "_" & jobTitle & "_" & Right$("000" & iCurrentPage, 4) & ".docx")
MsgBox strNewFileName
docSingle.SaveAs2 FileName:=strNewFileName, FileFormat:=wdFormatDocumentDefault
docSingle.Close SaveChanges:=wdSaveChanges 'close the new document
iCurrentPage = iCurrentPage + 1 'move to the next page
rngPage.Collapse wdCollapseEnd 'go to the next page
Loop 'go to the top of the do loop
Application.ScreenUpdating = True 'restore the screen updating
'Destroy the objects.
Set docMultiple = Nothing
Set docSingle = Nothing
Set rngPage = Nothing
End Sub
jobTitle
中删除。 With rngForFindSelect.Find
.Execute FindText:="Job Title"
If .Found = True Then
.Parent.Expand Unit:=wdSentence
.Parent.End = .Parent.End - 1
jobTitle = .Parent.Text
End If
End With