【问题标题】:Insert multiple TXT files into word with filename将多个 TXT 文件插入带有文件名的 word 中
【发布时间】:2021-12-14 07:10:06
【问题描述】:

我想在一个大的 docx 文档中插入多个 .txt 文件,文件名在每个 txt 文件的内容之前。

到目前为止,这很好用:

Sub A_Import_text()
Application.ScreenUpdating = False
Dim strFolder As String, strFile As String, wdDoc As Document, txtFile As Document
strFolder = GetFolder("")
If strFolder = "" Then Exit Sub
strFile = Dir(strFolder & "\*.txt", vbNormal)
Set wdDoc = ActiveDocument
While strFile <> ""
  Set txtFile = Documents.Open(FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False, ConfirmConversions:=False)
  wdDoc.Range.InsertAfter txtFile.Range.Text & vbCr
  txtFile.Close SaveChanges:=True
  strFile = Dir()
Wend
Set txtFile = Nothing: Set wdDoc = Nothing
Application.ScreenUpdating = True
End Sub


Function GetFolder(strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
    .Title = "Select a Folder"
    .AllowMultiSelect = False
    .InitialFileName = strPath
    If .Show <> -1 Then GoTo NextCode
    sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function

但我无法检索txt文件内容之前的文件名。

有人可以帮助我吗?

【问题讨论】:

  • wdDoc.Range.InsertAfter strFile &amp; vbCr &amp; txtFile.Range.Text &amp; vbCr
  • 效果很好,谢谢!

标签: vba ms-word extract


【解决方案1】:

您可以在插入的文本中添加带有回车符的文件名。

wdDoc.Range.InsertAfter strFile & vbCr & txtFile.Range.Text & vbCr

【讨论】:

    猜你喜欢
    • 2011-04-07
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多