【问题标题】:VBA: Copy lines from text file into Word docVBA:将文本文件中的行复制到 Word doc
【发布时间】:2020-07-03 06:59:35
【问题描述】:

通常我创建我的宏来记录功能,然后相应地调整它们,所以很遗憾我不知道如何去实现这个操作。

我有一些文本文件是账户档案;每个文件至少有 30k+ 行,每个文件有数百个(如果不是数千个)帐户。文档的第一行有账号,每个账号都被一个唯一的文本字符串分割。

目标是有一个宏,它在文本文件中查找,找到帐号,然后复制它下面的所有行,直到它到达唯一的分隔字符串,然后将它们粘贴到活动的 Word 文档中以供查看。

我不认为我会从这样一个模糊的问题中得到一个具体的答案,但是任何可以提供的指针都将不胜感激。

【问题讨论】:

    标签: vba ms-word text-files copy-paste


    【解决方案1】:

    这里有一个快速而肮脏的例子来说明原理......让文本文件名为“accounts.txt”,内容如下:

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

    现在让我们看一些使用Open AsLine 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多