这里有一个快速而肮脏的例子来说明原理......让文本文件名为“accounts.txt”,内容如下:
Account 1
item 1
item 2
item 3
=========
Account 2
item 4
item 5
=========
Account 3
item 6
item 7
=========
现在让我们看一些使用Open As 和Line Input 和循环结构的非常基本的VBA 代码......
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
你被另一个子叫这个
Sub test()
GetAccountFromTextFile "C:\Documents and Settings\MySelf\Desktop\accounts.txt", 1
GetAccountFromTextFile "C:\Documents and Settings\MySelf\Desktop\accounts.txt", 3
GetAccountFromTextFile "C:\Documents and Settings\MySelf\Desktop\accounts.txt", 2
End Sub
从 Word Doc 中的任意位置启动 test(),以下内容将粘贴到文档中:
Account 1
item 1
item 2
item 3
Account 3
item 6
item 7
Account 2
item 4
item 5
现在您可以在主子(可能是对话框)中非常有创意地了解如何在调用帐户获取器之前获取文件名和帐号,并且您需要修改查找帐号的条件和getter 中的分隔模式。不是很复杂,但应该足以让您继续前进。
祝你好运
迈克D