Click here to Skip to main content
15,896,498 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I programmatically select entire row in word document and delete it.

Example: I need rows from 1 to 37, and wanna to delete rows from 38-77. And I need to keep rows from 78 to 85.
Posted
Updated 26-Jul-12 3:00am
v2
Comments
mobydick66 27-Jul-12 6:20am    
Thank you very much.
I must do some modifications and after that it works.

1 solution

A good place to start is to record a macro from within Word.
Create 10 lines of text, start recording a macro then move down to the line you'd like to delete from. Once done, hold shift and keep pressing down until you have the desired text selected. Now press delete and stop the macro recording.

I did this and got some VBA code. Following that I recorded another macro that just captured the pressing of the Ctrl-Home key combination. After this I just recorded a macro of me typing 10 lines.

Putting them all together, I got a macro that would create 85 lines of text, before selecting lines 38-77 and deleting them.

This is VBA code - you can convert it to VB without terribly much fuss.


VB
Sub createThenDeleteText()
    Dim curLine As Integer
    Dim curStr As String
    
    ' create 85 lines of text
    For curLine = 1 To 85
        curStr = "Line" + Str(curLine) + vbCrLf
        Selection.TypeText (curStr)
    Next curLine
    
    ' move cursor back to start of document
    Selection.HomeKey Unit:=wdStory
    
    ' delete lines 38-77 inclusive
    Dim firstLine As Integer, lastLine As Integer
    firstLine = 38
    lastLine = 77
    Selection.MoveDown Unit:=wdLine, Count:=(firstLine - 1)
    Selection.MoveDown Unit:=wdLine, Count:=(lastLine - firstLine + 1), Extend:=wdExtend
    Selection.Delete Unit:=wdCharacter, Count:=1
End Sub
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900