2016-02-27 23 views
0

我正在處理單詞中的宏。它從excel文檔中的某些單元格中提取單元格內容,將其中的一部分放在單詞doc的末尾,加粗第一部分,然後放入其餘的字符串並取出它。然後,它會查找下一個匹配的excel doc並重復,直到沒有匹配。單詞vba範圍不使用循環重定位

在第二遍循環中,它繼續影響第一遍中添加的內容。帶塊的字體也會影響前一行,並最終加粗整個事物。我在該函數的末尾將該對象設置爲Nothing,因此我不希望它將該循環的第一部分視爲該範圍的一部分。

 Do 
     x = AssembleSentence(Last, First, Rank) 
     Set Loc = .FindNext(Loc) 
    Loop While Not Loc Is Nothing And Loc.Address <> sFirstFind 

Function AssembleSentence(Last, First, Rank) 
    Dim sText0 As String, sText As String, oText As Object 
    Set oText = ActiveDocument.Content 
    sText0 = First & " " & Last 
    sText = ", " & Rank & " Professor at College of Hard Knocks." 

    Set oText = ActiveDocument.Content.Paragraphs.Add 
    oText.Range.SetRange Start:=ActiveDocument.Range.End, End:=ActiveDocument.Range.End 
    Selection.EndKey Unit:=wdStory 

    With oText.Range 
     .InsertAfter (sText0) 
     With .Font 
      .Bold = True 
     End With 
    End With 

    Selection.EndKey Unit:=wdStory 

    With Selection 
     .Text = sText 
     With .Font 
      .Bold = False 
     End With 
    End With 

    Selection.EndKey Unit:=wdStory 

    Set oText = Nothing 

End Function 

回答

0

仍然不確定爲什麼循環不會重做範圍內自行結束,但這種修復它,使它停止之前影響循環的內容。

看着我的oText.range開始/結束屬性,它看起來像是1034/1035,第一遍的長度爲1036,然後是第二遍的長度爲1210的1036/1209。這是問題 - 我不知道爲什麼在第一次傳球結束時將對象設置爲無,但第二次傳球不是1208/1209,但以下編輯修復了問題。

With oText.Range 
    .SetRange Start:=oText.Range.End, End:=oText.Range.End 
    .InsertAfter (sText0) 
    With .Font 
     .Bold = True 
    End With 
End With 
+0

原因是.InsertAfter包含現有Range中的新內容。你也可以使用RANGE對象(Dim rng as Word.Range:Set rng = oText.Range)和* collapse * it:rng.Collapse wdCollapseEnd這是我的偏好,因爲它更明顯是怎麼回事。 –

+0

真棒解釋。謝謝! – Rodger