在 Excel 中使用 VBA 查找整个 Word 文档中的首字母缩写词

问题描述 投票:0回答:1

我想在 Excel 中使用 VBA 在整个 Word 文档中查找首字母缩略词。

Sub HighlightAcronyms()
    
    Dim rng As Range, r2 As Range
    
    Set rng = ActiveDocument.Content
    Set r2 = ActiveDocument.Content
    
    With rng.Find
        .ClearFormatting
        .Text = "<[A-Z]{2,}>"
        .Forward = True
        .Wrap = wdFindStop
        .MatchCase = True
        .MatchWildcards = True
        .Format = False
        
        Do While .Execute
            'look two characters past the found acroynm
            r2.Start = rng.End + 1
            r2.End = rng.End + 3
            Debug.Print rng.Text, r2.Text
            
            'highlight if r2 has a "(" otherwise clear highlight
            rng.HighlightColorIndex = IIf(r2.Text Like "*(*", _
                                          wdAuto, wdYellow)
        Loop
    End With
End Sub

On

.find
我收到编译错误

参数不是可选的

我试图声明

.find

excel vba ms-word
1个回答
0
投票

这是使用 Excel VBA 运行 Word VBA 代码的典型代码片段。请根据需要更新。

Sub WordVBAinExcel()
    Dim doc As Object ' Word.Document
    Dim wordApp As Object ' Word.Application

    On Error Resume Next
    ' Try to get the existing Word application
    Set wordApp = GetObject(, "Word.Application")
    On Error GoTo 0
    If wordApp Is Nothing Then
        ' If Word is not already running, create a new instance
        On Error Resume Next
        Set wordApp = CreateObject("Word.Application")
        On Error GoTo 0
    End If
    If wordApp Is Nothing Then
        MsgBox "Microsoft Word is not installed or accessible.", vbExclamation
        Exit Sub
    End If
    wordApp.Visible = True ' Set to True if you want to see the Word application during execution
    ' Open the Word document (Replace "C:\Path\to\Your\Document.docx" with the actual path)
    'Set doc = wordApp.Documents.Open("C:\Path\to\Your\Document.docx")
    
    'Your Code
    Dim rng As Object, r2 As Object ' it is wordApp.Range not Excel.Range
    
    Set rng = wordApp.ActiveDocument.Content
    Set r2 = wordApp.ActiveDocument.Content
    ' ....

    'Your Code

    ' Quit the Word application
    wordApp.Quit
    ' Clean up the objects
    Set doc = Nothing
    Set wordApp = Nothing
    MsgBox "Task completed.", vbInformation
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.