【问题标题】:Import tab-delimited text file and insert to a table in MS Word导入制表符分隔的文本文件并插入到 MS Word 中的表格中
【发布时间】:2022-07-08 07:02:07
【问题描述】:

我希望在 Microsoft Word 中编写一个 VBA 代码,该代码执行以下操作:

  • 导入制表符分隔的文本文件并确定其中的行数(列固定为 3)
  • 在活动 Word 文档中创建具有确定的行数和列数的表格,并将文本文件的内容粘贴到表格中。

到目前为止,我已经编写了以下 sn-p 来读取文本文件并在活动文档中创建表格。但是我不知道如何将文件的内容插入到表格中。

Dim FileContent As String

Const TextFile As String = "C:\Code\Input.txt"

Const BookmarkName As String = "ProfilesBegin"

Open TextFile For Input As #1
FileContent = Input(LOF(1), #1)
Close #1


' Getting the number of rows in the txt file
Const ForAppending = 8
Set FSO = CreateObject("Scripting.FileSystemObject")
Set theFile = FSO.OpenTextFile(TextFile, ForAppending, Create:=True)
txtrows = theFile.Line - 1
Set FSO = Nothing

' Inserting table in active document
Selection.GoTo What:=wdGoToBookmark, Name:="ProfilesBegin"
Selection.MoveDown Unit:=wdLine, Count:=1
Selection.InsertRows txtrows - 1

提前感谢您的帮助!

【问题讨论】:

  • 到目前为止你尝试过什么代码?你在哪里遇到了麻烦?请编辑您的问题以包含该内容。
  • 我已根据您的评论更新了问题。

标签: vba ms-word


【解决方案1】:

也许:

Sub InsertCSV_Tbl()
Dim Rng As Range
With ActiveDocument
  Set Rng = .Bookmarks("ProfilesBegin")
  With Rng
    .InsertFile FileName:="C:\Code\Input.txt", Range:=.Duplicate, ConfirmConversion:=False, Link:=False
    .ConvertToTable Separator:=vbTab
  End With
End With
End Sub

【讨论】:

    猜你喜欢
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    相关资源
    最近更新 更多