选择免费文件的目标文件夹

时间:2014-12-30 11:01:41

标签: excel vba file

下面的脚本不完整,因为我希望从用户之前选择的文件夹中打开目标文件。文件名已设置,但用户可以选择文件应驻留在哪个文件夹中。

本质上,此脚本的目标是从驻留在此文件中的Excel工作表创建管道分隔文件。随后,用户选择文件夹将文本文件保存到文件夹中。

Sub PipeDelimited()

    ' Exports to PipeDel.txt file
    Dim Rng As Range
    Dim ws As Worksheet
    Dim CurrRow As Range
    Dim CurrCell As Range
    Dim CurrTextStr As String
    Dim ListSep As String
    Dim DestFile As String

    ListSep = "|"

    Set ws = ThisWorkbook.Worksheets("jj")
    Set Rng = Worksheets("jj").UsedRange

    DestFile ====> use msoFileDialogFolderPicker??????
    File name is set under Cell d8 in the tab (sheet) called macros

    Open DestFile For Output As #1

    For Each CurrRow In Rng.Rows
        CurrTextStr = ""

        For Each CurrCell In CurrRow.Cells
            CurrTextStr = CurrTextStr & CurrCell.Value & ListSep
        Next

        While Right(CurrTextStr, 1) = ListSep
            CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
        Wend

        'Added next line to put | at end of each line
        CurrTextStr = CurrTextStr & ListSep
        Print #1, CurrTextStr
    Next
    Close #1
End Sub

我现在添加了这个sub,意图是vba脚本会自动将txt的后缀放到我的文件中。

下面的子项默认我的文件类型为txt。但是,当我点击确定时,没有任何反应。弹出窗口"请选择文件夹位置以保存此文件"每次我点击" ok"时弹出。但是,该文件没有保存。

Sub FolderLocation()

Dim folderpath As String
Dim fn As String
Dim fd As FileDialog

fn = ThisWorkbook.Worksheets("MACROS").Range("RngFileName").Value

Set fd = Application.FileDialog(msoFileDialogFilePicker)

fd.Title = "Please Choose Folder Location to Save this File"
fd.InitialFileName = ThisWorkbook.Worksheets("Macros").Range("RngFileName").Value
fd.AllowMultiSelect = False
fd.Filters.Add "All Files", "*.*"
fd.Filters.Add "Text", "*.txt", 1
fd.FilterIndex = 1
If fd.Show = True Then folderpath = fd.SelectedItems(1)


MsgBox "File Saved", vbOKCancel, folderpath

End Sub

1 个答案:

答案 0 :(得分:2)

根据您的代码调整此基本大纲。您需要将文件名连接到selectedFolder路径。

Sub getFolder()
Dim newFldrDia As FileDialog
Dim selectedFolder As String

Set newFldrDia = Application.FileDialog(msoFileDialogFolderPicker)

    With newFldrDia
        .Title = "My Dialog Title"
        .AllowMultiSelect = False
            If .Show = -1 Then
                selectedFolder = .SelectedItems(1)
            End If
    End With

MsgBox selectedFolder

End Sub

查看here了解更多可以使用的属性/方法。