读书人

vba在文本文件中找到指定的行后在

发布时间: 2012-02-11 09:51:34 作者: rapoo

vba在文本文件中,找到指定的行后,在该行前面插入内容(差一步,错误为'ERROR 要求对象)
前面一个网友的问题,花了很久时间 ,完成了一大部分, ,但就差这么一点!
错误为 'ERROR 要求对象 赋值问题,大家可以调一下

那位高手补充一下
---------
eg:
比如我有一文本文档:
aaaaaaaaaaaaaa
bbbbbbbbbb
ccccccccc
ddddddddd
eeeeeee
fffffff
ggggggggg
iiiiiiiiiiiiiiiii
zzzzzzzzzz
现在我需要的是:1,找到该文件iiiiiiiiiiiiiiii所在的行(i在第8行),然后在该行前面(第7行)插入内容hhhhhhhhhh。请问在vba中如何实现?
-------
Sub TEST()
Dim objWordApp As Object
Dim objWord As Object
Dim myRange As Object

Dim mySelection As Object

Set objWordApp = CreateObject("Word.Application")

Set objWord = objWordApp.Documents.Open("d:\测试文件.doc")


'遍历新生成的文档,定位到"iiiiiiiiiiiiiiiii",在其前面加入 hhhhhhh

Set myRange = objWord.Content

myRange.Find.ClearFormatting
myRange.Find.Execute findText:="iii", Forward:=True
If myRange.Find.Found = True Then

'myRange.InsertBefore "hhhhhhh" 在前面插入可以成功
Debug.Print myRange.Style
Set mySelection = myRange.Select 'ERROR 要求对象 ,

mySelection.InsertRowsAbove ' 插入一行
mySelection.typetext Text:="hhhhhhh"
End If


objWord.Close
objWordApp.Quit

End Sub

[解决办法]
参考下面在Word中手动操作
查找iiiiiiiiiiiiiiiii,光标移到本行开头,再移到上一行末尾,插入文本hhhhhhhhh。
录制的宏对应代码:
Selection.Find.ClearFormatting
With Selection.Find
.Text = "iiiiiiiiiiiiiiiii"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.MoveLeft Unit:=wdCharacter, Count:=2
Selection.TypeText Text:="hhhhhhhhh"

[解决办法]

你想象的“插入”是不存在的,实际上系统是重写了一个多一行的文件。如果是文本文件,没有必要动用 Word 对象:

Dim strLine As String

Open App.Path & "\1.txt" For Input As #1
Open App.Path & "\2.txt" For Output As #2
Do Until EOF(1)

Line Input #1, strLine
If strLine = "iiiiiiiiiiiiiiiii" Then Print #2, "hhhhhhh"
Print #2, strLine

Loop
Close #2
Close #1

Kill App.Path & "\1.txt"
Name App.Path & "\2.txt" As App.Path & "\1.txt"


[解决办法]

VB code
Sub test()'  Dim objWordApp As Object'  Set objWordApp = CreateObject("Word.Application")  Dim objWordApp As New Word.Application  Dim objWord As Word.Document  Dim myRange As Word.Range  Dim mySelection As Word.Selection  Set objWord = objWordApp.Documents.Open("d:\测试文件.doc")  Set myRange = objWord.Content    myRange.Select  Set mySelection = objWord.ActiveWindow.Selection    mySelection.Find.ClearFormatting  mySelection.Find.Execute findText:="iiiiiiiiiiiiiiiii", Forward:=True  If mySelection.Find.Found = True Then      With mySelection    '  .Collapse Direction:=wdCollapseEnd      .InsertParagraphBefore      .InsertBefore "hhhhhhh"      End With          objWord.Save  End If      objWord.Close  objWordApp.QuitEnd Sub 

读书人网 >VB

热点推荐