2015-06-10 57 views
0

我需要獲取當前滾動位置(我認爲這是正確的術語;即,我的虛擬透鏡指向文檔的位置,而不是我的光標所在的位置是)在Word文檔中,這樣當我運行一個宏時,我可以在最後返回到該位置。需要在MS Word中捕捉當前滾動位置(不是光標位置)

我寫了一個宏,它從當前光標位置向後搜索專利申請部件號,確定一個候選下一個可用部件號作爲先前的max + 1,然後搜索出現在光標下方的已排序數字列表以查看是否候選零件編號與下一個使用的編號發生衝突,如果確實如此,則會將候選零件編號加1並再次檢查碰撞,直到找到最小的未使用整數爲止,以儘可能地遵循引入零件的慣例說明書的主體按部件號順序排列。

然後它在當前光標位置插入該數字。它工作正常;但是,它會將當前行移動到查看窗口的頂部,這令人迷惑。我寧願保持滾動的位置。這裏是我的代碼:

Sub InsertLocalNextPartNum() 

Application.ScreenUpdating = False 

Dim re As VBScript_RegExp_55.RegExp 
Set re = New VBScript_RegExp_55.RegExp 


re.pattern = "\b(\d{2,3}\b)" 

'2-3位數字均含過的部分數了一下,但我的問題的目的,我們並不需要完整的正則表達式

re.IgnoreCase = False 
re.Global = True 

Dim txt As String 
Dim allLongMatches As MatchCollection, m As Match 
Dim nums() As Long 
Dim numsColl As New Collection 
Dim maxNum As Long 
maxNum = 0 
Dim nextPartNum As String 
Dim localNextPartNum As String 
localNextPartNum = 0 
Dim i As Long 
Dim j As Long 
Dim k As Long 


Selection.HomeKey Unit:=wdStory, Extend:=wdExtend 

txt = Selection.Range.text 

If re.Test(txt) Then 
     Set allLongMatches = re.Execute(txt) 
     For Each m In allLongMatches 

     numsColl.Add (m.Value) 

     Next m 
End If 
ReDim nums(1 To numsColl.Count) 

For i = 1 To numsColl.Count 
    nums(i) = numsColl(i) 
    If nums(i) > maxNum Then maxNum = nums(i) 
Next i 

localNextPartNum = maxNum + 1 


Selection.MoveRight 
Selection.EndKey Unit:=wdStory, Extend:=wdExtend 
txt = Selection.text 

If re.Test(txt) Then 
     Set allLongMatches = re.Execute(txt) 
     For Each m In allLongMatches 
     numsColl.Add (m.Value) 
     Next m 
End If 

ReDim nums(1 To numsColl.Count) 
Dim numTemp As String 
Dim lngMin As Long 
Dim lngMax As Long 
lngMin = LBound(nums()) 
lngMax = UBound(nums()) 

For i = 1 To numsColl.Count 
    nums(i) = numsColl(i) 
Next i 

For j = lngMin To lngMax - 1 
    For k = j + 1 To lngMax 
     If nums(j) > nums(k) Then 
     numTemp = nums(j) 
     nums(j) = nums(k) 
     nums(k) = numTemp 
     End If 
    Next k 
Next j 

For i = 1 To numsColl.Count 
    If localNextPartNum < nums(i) Then Exit For 
    ' Debug.Print nums(i) 
    If localNextPartNum = nums(i) Then localNextPartNum = nums(i) + 1 
Next i 
Selection.MoveLeft 
Selection.InsertAfter (localNextPartNum & " ") 
Selection.MoveRight 

End Sub 
+0

還必須有一種方法可以通過參考搜索已使用的零件號的範圍來實現我所要做的事情,而不必將選擇範圍擴大到這些範圍的範圍。 – PatentWookiee

回答

1

捕獲的窗口滾動位置使用:

scrollPosition = ActiveWindow.ActivePane.VerticalPercentScrolled 

將它恢復到原來的用途:

ActiveWindow.ActivePane.VerticalPercentScrolled = scrollPosition