用于删除Word doc中文本的代码 [英] code for deleting text in word doc

查看:126
本文介绍了用于删除Word doc中文本的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式在Word文档中选择整行并将其删除.

示例:我需要从1到37的行,并想从38-77删除行.而且我需要将行数从78保留到85.

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.

推荐答案

一个好的开始是从Word中记录宏.
创建10行文本,开始记录宏,然后向下移至您要删除的行.完成后,按住Shift键并按住不放,直到选择了所需的文本.现在按Delete键并停止宏录制.

我这样做了,并得到了一些VBA代码.之后,我录制了另一个宏,该宏仅捕获了Ctrl-Home组合键的按下.之后,我只是记录了我键入10行的宏.

将它们放在一起,我得到一个可以创建85行文本的宏,然后选择38-77行并将其删除.

这是VBA代码-您可以毫不费力地将其转换为VB.


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.


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


这篇关于用于删除Word doc中文本的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆