簡體   English   中英

Word VBA:根據條件語句修改范圍

[英]Word VBA: Modify range based on conditional statement

我正在編寫一個腳本,該腳本從 Word 文檔中提取括號內的文本引用,例如“(作者,1992 年)”,並將它們復制到另一個文檔。 該代碼可以很好地提取所有括號,但在某些情況下,引用的形式為“如作者(1992 年)中引用的那樣......”如果括號以數字開頭,我想將前一個詞拉入范圍並將兩者都復制到新文檔中。 那么在上面的場景中,我們將得到“Author (1992)”,而不僅僅是代碼當前運行的“(1992)”。 我已經嘗試編寫一個條件來使用.MoveStart修改范圍,但是當范圍復制到新文檔時它沒有捕獲前面的詞。 我知道我在這里遺漏了一些小而重要的部分,但在其他論壇問題上找不到任何明顯的(對我來說)解決方案。 謝謝

Sub CopyRefs()
  Dim SearchRange As Range, DestinationDoc$, SourceDoc$
  DestinationDoc$ = "Extracted_References.doc"
  SourceDoc$ = ActiveDocument.Name
  Documents.Add DocumentType:=wdNewBlankDocument
  ActiveDocument.SaveAs DestinationDoc$, wdFormatDocument
  Documents(SourceDoc$).Activate
  Set SearchRange = ActiveDocument.Range
    
  With SearchRange.Find
      Do While .Execute(findText:="\(*\)", _
        MatchWildcards:=True, _
        Wrap:=wdFindStop, Forward:=True) = True
             
          'this part doesn't seem to work when condition is satisfied 
          If SearchRange.Text Like "\(#*" Then 
              SearchRange.MoveStart wdWord, -1
          End If
          
          'a parenthetical number like (1992) will copy over to new doc but seems_
          'like range not updating to include preceding word in previous step
          Documents(DestinationDoc$).Range.InsertAfter SearchRange.Text & vbCr
      Loop
  End With
End Sub

感謝 jonsson 指出語法錯誤。 下面的代碼按預期運行。

Sub CopyRefs()
  Dim SearchRange As Range, DestinationDoc$, SourceDoc$
  DestinationDoc$ = "Extracted_References.doc"
  SourceDoc$ = ActiveDocument.Name
  Documents.Add DocumentType:=wdNewBlankDocument
  ActiveDocument.SaveAs DestinationDoc$, wdFormatDocument
  Documents(SourceDoc$).Activate
  Set SearchRange = ActiveDocument.Range

  With SearchRange.Find
      Do While .Execute(findText:="\(*\)", _
        MatchWildcards:=True, _
        Wrap:=wdFindStop, Forward:=True) = True
             
          'Removed backslash since "(" doesn't need to be escaped
          If SearchRange.Text Like "(#*" Then
              SearchRange.MoveStart wdWord, -1
          End If
          
          'copies range to new doc
           Documents(DestinationDoc$).Range.InsertAfter SearchRange.Text & vbCr
           
          'collapses range to prevent infinite loop when If condition met
          SearchRange.Collapse wdCollapseEnd
      Loop
  End With
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM