我目前正在編寫一個vba宏,它應該抓住文檔中的所有註釋並將它們返回到新創建的excel文件中。我差不多完成了,但遇到了段落指示問題。我想把段落相應的標題放在excel中。爲了做到這一點,我必須直接得到段落標題,或者在段落上方找到第一個與標題相關的格式。至少這些是我能想到的選項。任何想法如何最好地解決這個問題?如何使用vba返回單詞上面第一個標題的值?
Sub exportComments()
Dim xlApp As Object
Dim xlWB As Object
Dim i As Integer, HeadingRow As Integer
Dim objPara As Paragraph
Dim objComment As Comment
Dim strSection As String
Dim strTemp
Dim myRange As Range
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWB = xlApp.Workbooks.Add 'create a new workbook
With xlWB.Worksheets(1)
' Create Heading
HeadingRow = 1
.Cells(HeadingRow, 1).Formula = "Comment"
.Cells(HeadingRow, 2).Formula = "Page"
.Cells(HeadingRow, 3).Formula = "Paragraph"
.Cells(HeadingRow, 4).Formula = "Commented part"
.Cells(HeadingRow, 5).Formula = "Comment"
.Cells(HeadingRow, 6).Formula = "Reviewer"
.Cells(HeadingRow, 7).Formula = "Date"
strSection = "preamble" 'all sections before "1." will be labeled as "preamble"
strTemp = "preamble"
If ActiveDocument.Comments.Count = 0 Then
MsgBox ("No comments")
Exit Sub
End If
For i = 1 To ActiveDocument.Comments.Count
Set myRange = ActiveDocument.Comments(i).Scope
strSection = ParentLevel(myRange.Paragraphs(1))
'MsgBox strSection
'Comment line
.Cells(i + HeadingRow, 1).Formula = ActiveDocument.Comments(i).Index
'Page number line
.Cells(i + HeadingRow, 2).Formula = ActiveDocument.Comments(i).Reference.Information(wdActiveEndAdjustedPageNumber)
'Paragraph indicator line
.Cells(i + HeadingRow, 3).Formula = ActiveDocument.Comments(i).Scope.Paragraphs(1)
'Commented part line
.Cells(i + HeadingRow, 4).Formula = ActiveDocument.Comments(i).Scope.FormattedText
'Comment value line
.Cells(i + HeadingRow, 5).Formula = ActiveDocument.Comments(i).Range
'Comment reviewer line
.Cells(i + HeadingRow, 6).Formula = ActiveDocument.Comments(i).Author
'Comment date line
.Cells(i + HeadingRow, 7).Formula = Format(ActiveDocument.Comments(i).Date, "dd/MM/yyyy")
Next i
End With
Set xlWB = Nothing
Set xlApp = Nothing
End Sub
Function ParentLevel(Para As Word.Paragraph) As String
' Finds the first paragraph of the current section
Dim oSection As Section
Dim iSection As Integer
Dim lngPara As Long
Dim oRng As Range, oPara As Range
iSection = Para.Range.Information(wdActiveEndSectionNumber)
Set oSection = ActiveDocument.Sections(iSection)
Set oRng = oSection.Range
For lngPara = 1 To oRng.Paragraphs.Count
Set oPara = oRng.Paragraphs(lngPara).Range
If Len(oPara) > 1 Then
Exit For
End If
Next lngPara
oPara.End = oPara.End - 1
ParentLevel = oPara.Text
End Function
這樣的想法是把段落標題在Headingrow 3.該解決方案必須適應不同的頭格式,我經常有自制的頭格式工作的文件。我唯一可以信賴的就是在樣式名稱中包含單詞標題的標題。任何幫助將不勝感激,當然我可以添加更多的信息可能會失蹤。
如果需要此信息,我使用word 2016 –