【问题标题】:import folder of .txt files into word document将.txt文件的文件夹导入word文档
【发布时间】:2015-08-10 04:03:32
【问题描述】:

我发现很多关于将 .txt 文件的文件夹导入到 excel 中,但在将 .txt 文件导入到 word 中的情况并不多。我试图让我的宏打开特定文件夹中的所有 .txt 文件并将它们导入到单个 word 文档中,每个 .txt 文件都有自己的页面。这是我到目前为止的代码(我在网上找到的):

Sub AllFilesInFolder()
    Dim myFolder As String, myFile As String
    myFolder = Application.FileDialog(msoFileDialogFolderPicker)
    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        .Show
        If .SelectedItems.Count > 0 Then
            myFolder = .SelectedItems(1)
        End If
    End With
    myFile = Dir(myFolder & "\*.txt") '
    Do While myFile <> ""
        Open myFolder & "\" & myFile For Input As #1
        'Copy & Paste Macro?
        myFile = Dir
    Loop
End Sub

【问题讨论】:

  • 很好地找到了代码。现在告诉我们您在代码中遇到了哪些问题以及您尝试对其进行哪些更改以使其正常工作:)
  • Word 有一个 Insert ► Text ► Object ► Text from File 命令更适合从文件中插入文本。如果您录制自己带入一两个 TXT 文件,其余的应该很明显。如果遇到问题,请回来。

标签: vba automation ms-word


【解决方案1】:

这里有一些东西可以帮助你开始

Word 2010

编辑这应该允许您打开一个文档中的所有 txt 文件并保存

Option Explicit
Sub AllFilesInFolder()
    Dim myFolder    As String
    Dim myFile      As String
    Dim wdDoc       As Document
    Dim txtFiles    As Document

    Application.ScreenUpdating = False

    myFolder = openFolder

    If myFolder = "" Then Exit Sub

    myFile = Dir(myFolder & "\*.txt", vbNormal)
    Set wdDoc = ActiveDocument

    While myFile <> ""
        Set txtFiles = Documents.Open(FileName:=myFolder & "\" & myFile, AddToRecentFiles:=False, Visible:=False, ConfirmConversions:=False)
        wdDoc.Range.InsertAfter txtFiles.Range.Text & vbCr
        txtFiles.Close SaveChanges:=True
    myFile = Dir()
    Wend

    Set txtFiles = Nothing
    Set wdDoc = Nothing

    Application.ScreenUpdating = True
End Sub     
Function openFolder() As String

    Dim oFolder     As Object

    openFolder = ""

    Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
        If (Not oFolder Is Nothing) Then openFolder = oFolder.Items.Item.Path

    Set oFolder = Nothing
End Function

【讨论】:

  • 谢谢!此代码将每个文本文件作为单独的 word 文档打开,但我想知道如何将其放入单个文档中。我添加了 objDoc.SaveAs ("P:\ImportedDescriptions.doc") 作为保存文档的尝试,但它只保存了最后一个。我的代码应该保存每个新文档然后将其合并为一个,还是可以直接将文本文件导入一个文档?任何建议将不胜感激!
  • 会涉及到创建数组吗?
【解决方案2】:

使用命令提示符 (cmd.exe) 和以下命令将所有文本文件复制到一个文件中:

copy *.txt NewFile.txt

然后用word打开这个文件,修改你想看文字的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多