Question

I have a macro that I use to highlight lines of to do lists to see which step I am on. It's pretty simple. It unhighlights the current line and highlights 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 unhighlight 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 the whole thing (minus the sub statements) which first checks if it's the last line. But, I don't know how to check if a line is the last line. I have googled and haven't found anything.

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

Thanks for any help

Was it helpful?

Solution

I'm not sure if this is the exact logic you need but this code presenting one of possible way of checking if you are in last line of 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 empty paragraph moves end of document somewhere below your the last line of your TEXT.

OTHER TIPS

Another approach one could take is to set take advantage of the MoveDown method's ability to return a variable. If, instead of:

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

you write:

c = Selection.MoveDown(wdLine,1) ,

then the variable c will assume a value equal to however many units the selection actually moves. So, as long as the selection is in the body of the text, it moves down one line and c = 1. Whereas, at the end of text, the selection can't move down another line, and so c = 0. That way you set up a simpler control condition:

If c = 0 then...

Do until c = 0...

etc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top