将文件名导入Word表列1 - 1每行文件名

时间:2016-04-20 16:45:36

标签: vba file ms-word word-vba

我正在尝试将文件名导入到word表中。有许多脚本可以将文件导入Excel,但没有字表:(

我将浏览文件夹>然后将文件名导入第1列

每个表格行1个文件名

我被困在如何将文件名导入或插入表格中。

Sub ImportFileName()
    Dim getFolder As String
    Dim myFile As String
    Dim myDoc As Document
    Dim aTable As Table
    Application.ScreenUpdating = False
    getFolder = getFolder
    If getFolder = "" Then Exit Sub
    myFile = Dir(getFolder & "\" & "*.doc*", vbNormal)
    Set aTable = ActiveDocument.Tables(1)
    While myFile <> ""
        Set myDoc = Documents.Open(getFolder & "\" & myFile)
        'How do I import the file name into table column 1
        aTable.Rows.Add
        myDoc.Close wdDoNotSaveChanges
        myFile = Dir()
        Set myDoc = Nothing
        Application.ScreenUpdating = True
    End Sub

如何将文件名导入字表?

1 个答案:

答案 0 :(得分:0)

您已拥有文件名。它位于myFile

aTable.Rows.Add之后,光标位于新行的第一个单元格中。只需将其插入Selection.InsertAfter myFile

编辑:

Word中的以下子插入一个新的3列表并列出所有文件名。

Sub ListFilenames()
Dim myFile As String, getFolder As String

    getFolder = "<set your folder here>"
    myFile = Dir(getFolder & "\" & "*.doc*", vbNormal)

    ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:=3

    While myFile <> ""
        Selection.InsertAfter (myFile): Selection.MoveRight Unit:=wdCell
        Selection.InsertAfter ("Col2"): Selection.MoveRight Unit:=wdCell
        Selection.InsertAfter ("Col3"): Selection.MoveRight Unit:=wdCell    ' this inserts a new row
        myFile = Dir()
    Wend

End Sub