以下の例では、Word VBA を使用して Excel にアクセスし、ワークシート データを取得します。これを使用して、ドキュメント内で強調表示する範囲を定義します。このコードを機能させるには、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
お役に立てれば。