提示用户选择多个文件并对所有文件

时间:2018-05-17 02:39:36

标签: vba excel-vba multiple-files excel

用户有数百个文本文件,需要对数据进行更改,然后保存并关闭它们。

下面是我对单个文件的代码,如何让它处理多个文件?

Sub transformTxt()
    vFileName = Application.GetOpenFilename("Text Files (*.edi),*.txt") 'prompt file selection
    Workbooks.OpenText Filename:=vFileName, _
                       Origin:=xlMSDOS, StartRow:=1, DataType:=xlDelimited, _
                       TextQualifier:=xlDoubleQuote, _
                       ConsecutiveDelimiter:=False, Tab:=False, _
                       Semicolon:=False, Comma:=False, Space:=False, _
                       Other:=True, OtherChar:="*", TrailingMinusNumbers:=True, _
                       Local:=True                              'open *delimited txt in excel

    Call Transform                                      'replace values in prompt file

    ActiveWorkbook.SaveAs Filename:=SaveToDirectory & ActiveWorkbook.Name & ".xls", _
                          FileFormat:=xlWorkbookNormal
    ActiveWorkbook.Close                                  'save and close it
End Sub

1 个答案:

答案 0 :(得分:3)

Application.FileDialogAllowMultiSelect = True

一起使用
Sub SelectMultipleFiles()
    Dim fDialog As FileDialog
    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    With fDialog
        .AllowMultiSelect = True
        .Title = "Please select the files"
        .Filters.Clear
        .Filters.Add "All supported files", "*.txt;*.edi"
        .Filters.Add "Text Files", "*.txt"
        .Filters.Add "EDI files", "*.edi"

        If .Show = True Then
            Dim fPath As Variant
            For Each fPath In .SelectedItems
                ' Use 'fPath' to do whatever you want.
            Next
        End If
    End With
End Sub

希望有所帮助。