2011-05-23 137 views
0

通常我會創建我的宏,然後對它們進行相應的調整,因此我不知道如何去實現此操作。VBA:將文本文件中的行復制到Word文檔中

我有一些文本文件是帳戶的檔案;每個文件至少有30k +行,並且每個文件中有數百個(如果不是數千個)帳戶。文檔中的第一行有帳號,每個帳號除以唯一的文本字符串。

目標是在文本文件中查找宏,找到帳號,然後複製下面的所有行,直到它到達唯一的分隔字符串,並將它們粘貼到活動的Word文檔中進行查看。

我不認爲我會從這樣一個模糊的問題中得到一個具體的答案,但任何可以提供的指針將不勝感激。

回答

1

這裏有一個快速&葷一來說明的原則....讓文本文件被稱爲「accounts.txt」具有以下內容:

Account 1 
item 1 
item 2 
item 3 
========= 
Account 2 
item 4 
item 5 
========= 
Account 3 
item 6 
item 7 
========= 

現在讓我們看一些非常基本的VBA代碼利用的Open AsLine 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

相關問題