【问题标题】:How to add Directory Chooser to macro如何将目录选择器添加到宏
【发布时间】:2014-01-29 20:48:49
【问题描述】:

我不想对目录进行硬编码,而是想打开一个目录选择器功能,以便用户可以为以下内容选择源文件夹和目标文件夹:

Sub XlsToTxt()
    Dim aFile As String
    Const SourceFolder = "C:\Users\Documents\PCS\" ' note the backslash at the end of the string
    Const targetFolder = "C:\Users\Desktop\PCS Text\" ' note the backslash at the end of the string
    Application.DisplayAlerts = False
    aFile = Dir(SourceFolder & "*.xls")
    Do While aFile <> ""
        Workbooks.Open SourceFolder & aFile
        ActiveWorkbook.SaveAs targetFolder & Left(aFile, Len(aFile) - 4) _
        & ".csv", FileFormat:=xlCSV _
        , CreateBackup:=False
        ActiveWorkbook.Close
        aFile = Dir
    Loop
    Application.DisplayAlerts = True
End Sub

【问题讨论】:

标签: excel directory vba


【解决方案1】:

试试这个:

Sub XlsToTxt()
    Dim aFile As String
    Dim SourceFolder As String
    Dim targetFolder As String

    With Application.FileDialog(msoFileDialogFolderPicker)
      .AllowMultiSelect = False
      .Title = "Select Source folder"
      .Show
      On Error Resume Next
      SourceFolder = .SelectedItems(1) & "\"
      On Error GoTo 0
    End With
    With Application.FileDialog(msoFileDialogFolderPicker)
      .AllowMultiSelect = False
      .Title = "Select Target folder"
      .Show
      On Error Resume Next
      targetFolder = .SelectedItems(1) & "\"
      On Error GoTo 0
    End With

    If SourceFolder = "" Or targetFolder = "" Then Exit Sub

    Application.DisplayAlerts = False
    aFile = Dir(SourceFolder & "*.xls")
    Do While aFile <> ""
        Workbooks.Open SourceFolder & aFile
        ActiveWorkbook.SaveAs targetFolder & Left(aFile, Len(aFile) - 4) _
        & ".csv", FileFormat:=xlCSV _
        , CreateBackup:=False
        ActiveWorkbook.Close
        aFile = Dir
    Loop
    Application.DisplayAlerts = True
End Sub

【讨论】:

    【解决方案2】:

    这个:fnameandpath = Application.GetOpenFilename(Title:="Select File")

    将打开一个文件选择器对话框,供用户选择源文件和目标文件。他们可以正常浏览,并且在选择文件时会返回完整路径和文件名进行处理

    编辑

    添加过滤器 - fnameandpath = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls), *.xls",Title:="Select File")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-09
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2018-02-21
      • 1970-01-01
      • 2017-04-06
      相关资源
      最近更新 更多