合并文件

时间:2017-10-12 09:22:22

标签: excel excel-vba vba

我想合并特定文件夹中的所有Excel文件。我为文件夹的路径创建了一个输入框,我要合并文件。然后我有文件名的公式,该公式不起作用。它给出了值Filename=""。为什么会这样?如何解决?

Dim Path as String
Dim Filename as String

Path = InputBox("Paste the path of the folder with files to consolidate")

Filename = Dir(Path & "*.xls*", vbNormal)

1 个答案:

答案 0 :(得分:1)

Why not use Excel's own folder picker? Try this code.

Function PickedFolder() As String

    Dim Dlg As FileDialog
    Dim Ffn As String

    Ffn = Application.DefaultFilePath & "\"
    Set Dlg = Application.FileDialog(FileDialogType:=msoFileDialogFolderPicker)
    With Dlg
        .Title = "Select the folder to consolidate"
        .InitialView = msoFileDialogViewList
        .InitialFileName = Ffn
        .AllowMultiSelect = False
        If .Show = True Then PickedFolder = .SelectedItems(1)
    End With
End Function

The function returns the path the user selects. You can enter it in your text box or proceed directly to consolidate the files found in it.