VBA:将文本文件中的行复制到Word文档中
问题描述:
通常我会创建我的宏,然后对它们进行相应的调整,因此我不知道如何去实现此操作。VBA:将文本文件中的行复制到Word文档中
我有一些文本文件是帐户的档案;每个文件至少有30k +行,并且每个文件中有数百个(如果不是数千个)帐户。文档中的第一行有帐号,每个帐号除以唯一的文本字符串。
目标是在文本文件中查找宏,找到帐号,然后复制下面的所有行,直到它到达唯一的分隔字符串,并将它们粘贴到活动的Word文档中进行查看。
我不认为我会从这样一个模糊的问题中得到一个具体的答案,但任何可以提供的指针将不胜感激。
答
这里有一个快速&荤一来说明的原则....让文本文件被称为“accounts.txt”具有以下内容:
Account 1
item 1
item 2
item 3
=========
Account 2
item 4
item 5
=========
Account 3
item 6
item 7
=========
现在让我们看一些非常基本的VBA代码利用的Open As
和Line Input
和循环结构....
Sub GetAccountFromTextFile(FileName As String, Accnt As String)
Dim MyLine As String, State As String
Open FileName For Input As #1
State = "Searching" ' we could make this much simpler but
' want to illustrate the different stati
' the loop is reaching
Do While Not (EOF(1) Or State = "End")
Line Input #1, MyLine ' read next line from text file
' now process as function of
' content and current state
If State = "Reading" And MyLine = "=========" Then
State = "End"
ElseIf MyLine = "Account " & Accnt Then
Selection.InsertAfter "Account " & Accnt & vbCrLf
State = "Reading"
ElseIf State = "Reading" Then
Selection.InsertAfter MyLine & vbCrLf
End If
Loop
Close #1
End Sub
您可以通过另一个子称之为
如何Account 1
item 1
item 2
item 3
Account 3
item 6
item 7
Account 2
item 4
item 5
现在你可以在你的主子很有创意(也许是对话形式):
启动测试()在一个Word文档的任何地方,而下面将要粘贴到文档要获取文件名和帐号,然后才能调用帐号获取器,并且需要修改用于查找帐号和分离模式的条件。不是很复杂,但应该足以让你去。
祝你好运 MikeD