在Excel中插入所有文件名

时间:2020-08-11 18:44:28

标签: excel vba

我需要一个代码,该代码将插入保存在excel路径中的所有文件名

我只为excel文件编写了一个代码,但我需要获取所有文件名。

Sub NameInFile()

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(Range("F4").Value)
    iRow = 2
    On Error Resume Next
    For Each myfile In f.Files
        If myfile.Name Like "*.xls?" Then
            Cells(iRow, 40).Value = myfile.Name
            iRow = iRow + 1
            N = N + 1
        End If
    Next myfile
    Columns("AL").AutoFit
    
Range("D9").Interior.ColorIndex = 43

End Sub

1 个答案:

答案 0 :(得分:1)

您需要从代码中删除If..end if条件。

您的代码应如下所示,我还删除了代码中未使用的冗余N变量。

Sub NameInFile()

Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(Range("F4").Value)
iRow = 2
On Error Resume Next
For Each myfile In f.Files
    '\\ If condition is removed
    Cells(iRow, 40).Value = myfile.Name
    iRow = iRow + 1
Next myfile
Columns("AL").AutoFit

Range("D9").Interior.ColorIndex = 43

End Sub
相关问题