如何将焦点返回到宏文件从宏打开Excel文件的Word文档

时间:2016-04-20 04:48:28

标签: excel vba ms-word word-vba

Private Sub CommandButton1_Click()
Dim oRng As Word.Range
Dim arrExcelValues()
Dim i As Long
Dim x As Long

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Risk Words.xlsx")
objExcel.Visible = False

i = 1
x = 0

Do Until objExcel.Cells(i, 1).Value = ""
   ReDim Preserve arrExcelValues(x)
   arrExcelValues(x) = objExcel.Cells(i, 1).Value
   i = i + 1
   x = x + 1
Loop
objExcel.Quit

For i = 0 To UBound(arrExcelValues)
    Set oRng = ActiveDocument.Range
    Options.DefaultHighlightColorIndex = wdYellow
    With oRng.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = arrExcelValues(i)
        .MatchWholeWord = True
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll
    End With
Next
End Sub

编写此代码以从Excel文件中选择单词并在Word文件中检查它以查看它们是否存在并突出显示它们。但是,它似乎不适用于Set oRng = ActiveDocument.Range。虽然,如果我之前放了一个MsgBox,它确实会显示从Excel中获取的值并存储在数组中。

1 个答案:

答案 0 :(得分:0)

如果您从Word文档调用宏,则在打开Excel文件之前设置oRng可能会有所帮助。或者您可以在尝试写入Word之前放置Word.Application.Activate