Somehow specify the last line in Word VBA

I have a macro that I use to highlight lines of lists to see what stage I am at. It is pretty simple. It selects the current line and selects the next line.

Sub Highlight_Next_Row_Down() Selection.EndKey Unit:=wdLine Selection.HomeKey Unit:=wdLine, Extend:=wdExtend Selection.Range.HighlightColorIndex = wdNoHighlight Selection.MoveDown Unit:=wdLine, Count:=1 Selection.EndKey Unit:=wdLine Selection.HomeKey Unit:=wdLine, Extend:=wdExtend Selection.Range.HighlightColorIndex = wdYellow End Sub 

Now I want it to just highlight the current line when I am on the last line of the document, because then I am finished. I would do this by inserting an if statement around all of this (minus the auxiliary statements), which first checks if this is the last line. But I do not know how to check if a line is the last line. I googled and found nothing.

Similarly, I have "Highlight_Next_Row_Up" and I want to know how to do the same when I reach the top line.

Thanks for any help

+4
source share
2 answers

I'm not sure if this is the exact logic you need, but this code represents one of the possible ways to check if you are on the last line of the document.

 Sub Highlight_Next_Row_Down() Selection.EndKey Unit:=wdLine Selection.HomeKey Unit:=wdLine, Extend:=wdExtend 'here check if this is the end If Selection.End = ActiveDocument.Bookmarks("\EndOfDoc").Range.End Then 'just unhighlight Selection.Range.HighlightColorIndex = wdNoHighlight Else 'your code here Selection.Range.HighlightColorIndex = wdNoHighlight Selection.MoveDown Unit:=wdLine, Count:=1 Selection.EndKey Unit:=wdLine Selection.HomeKey Unit:=wdLine, Extend:=wdExtend Selection.Range.HighlightColorIndex = wdYellow End If End Sub 

Please keep in mind that any additional blank paragraph moves end of document somewhere below your last line of your TEXT.

+3
source

Another approach you can take is to take advantage of the MoveDown method to return the variable. If instead of:

Selection.MoveDown Unit: = wdLine, Count: = 1,

you write:

c = Selection.MoveDown (wdLine, 1),

then the variable c takes a value equal to any number of units that actually move. So, while the selection is in the text, it moves one line and c = 1. If at the end of the text the selection cannot move along another line, and therefore c = 0. This is what you set up a simpler control condition:

If c = 0, then ...

Until c = 0 ...

etc.

0
source

Source: https://habr.com/ru/post/1480795/


All Articles