【发布时间】: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 & vbCr & txtFile.Range.Text & vbCr -
效果很好,谢谢!