根据要突出显示的段落组编号列表,在MS-Word doc中突出显示段落?

时间:2012-06-26 17:40:23

标签: database excel ms-word reporting highlighting

我有几页的MS-Word文档,其中每个段落都有一个新的段落编号。见下面的例子。另外,在MS-Excel或CSV文件中,我有两列信息 - 段落编号以及是否应该突出显示:

Paragraph Number, Highlight?

1, True
2, False
3, True

在Word文档中突出显示的控制列表中,最简单的方法是以“True”列出的段落?

All about fruits

Apples

Paragraph group 1

Each person shall eat one apple a day to keep the doctor away.

Note: Apples are a red fruit.

Apples have been growing for a long time. Sometimes they fall off the tree by themselves. Sometimes you have to pick them.

Pears

Paragraph group 2

Pears shall be sliced before being eaten.

Pears are usually green, and better when a little soft.

Note: Pears have a distinctive shape

Tomatoes

Paragraph group 3

Tomatoes shall be washed before being eaten.

Note: Tomatoes really are a fruit, not a vegetable.

Or rather, vegetable is not a scientific term. It is a common term.

1 个答案:

答案 0 :(得分:0)

下面的示例使用Word VBA访问Excel并获取工作表数据,然后使用该数据定义文档中突出显示的范围。为了使此代码有效,请确保引用 Microsoft Excel 14.0对象库

Microsoft Excel 14.0 Object Library

Public Sub HighlightParaGroups()

Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Dim x As Integer
Dim r As Integer 'Total rows of data
Dim rngStartPoint As Range
Dim rngEndPoint As Range

Set xlApp = CreateObject("Excel.Application")
'Hard coded path to Excel worksheet
Set xlWB = xlApp.Workbooks.Open("C:\Users\Joe\Desktop\SO Data Test.xlsx")
Set xlWS = xlApp.Worksheets(1)

'This is the hard coded amount of rows for the example given.
'If row amount will vary, write a sub to detect range of data
r = 3
ActiveDocument.Select

For x = 1 To r
    Debug.Print xlWS.Cells(x, 2)
    If xlWS.Cells(x, 2) = "True" Then 'test for values to highlight
        Set rngStartPoint = DefineHighlightRange(x, True)
        If x + 1 <= r Then
            x = x + 1
            Set rngEndPoint = DefineHighlightRange(x, False)
            x = x - 1
        Else 'In case last paragraph needs to be highlighted
            ActiveDocument.Characters.Last.Select
            Selection.Collapse
            Set rngEndPoint = Selection.Range
        End If
        rngStartPoint.SetRange Start:=rngStartPoint.Start, End:=rngEndPoint.Start
        rngStartPoint.HighlightColorIndex = wdYellow
    End If
Next

xlWB.Close False ' close the workbook without saving
xlApp.Quit ' close the Excel application
Set xlWB = Nothing
Set xlApp = Nothing

End Sub

以下是用于定义范围的函数:

Public Function DefineHighlightRange(x As Integer, DecisionFlag As Boolean) As Range

'DecisionFlag determines if the selection needs to be 
'repositioned for the start point of the range
Selection.Find.Text = "Paragraph group " & x
Selection.Find.Execute
Selection.HomeKey
If DecisionFlag = True Then
    Selection.MoveDown Unit:=wdLine, Count:=1
End If
Set DefineHighlightRange = Selection.Range

End Function

希望这有帮助。