如何在VBA中将生成的输出文本文件保存在用户所选文件夹中?

时间:2017-10-17 17:02:26

标签: excel vba excel-vba

我创建了一个VBA代码,用于生成文本文件。我将7个参数传递给子方法以生成所有文本文件。但是,我很难将生成的文件保存到用户选择的文件夹中。当我运行代码时,它只是将所有文件保存到包含的路径中(现在因为我不知道如何做我上面解释的内容)。

下面是我的代码,我试图合并路径,让任何用户选择一个文件夹来保存所有生成的文本文件。

Sub TextFiles()

Dim fso As Scripting.FileSystemObject, Path As String

'Ask user to save files into a folder
Path = "C:\Users\samplename\Desktop\TEST"


'Call sub procedure to generate text files and store them in NewFolderPath
CreateTxtFiles.CreateTxtFiles Path & "\sample1.txt", 1, "sample1", "sample1_", 7, "sample1_2", 9
CreateTxtFiles.CreateTxtFiles Path & "\sample2.txt", 2, "sample2", "sample2_", 9, "0", 0
CreateTxtFiles.CreateTxtFiles Path & "\sample3.txt", 3, "sample3", "sample3", 5, "0", 0
CreateTxtFiles.CreateTxtFiles Path & "\sample4.txt", 4, "sample4", "sample4", 5, "0", 0

End Sub

2 个答案:

答案 0 :(得分:1)

这样的事情对你有用:

Sub tgr()

    Dim ShellFolderPicker As Object
    Dim FolderPath As String

    Set ShellFolderPicker = CreateObject("Shell.Application")
    On Error Resume Next
    FolderPath = ShellFolderPicker.BrowseForFolder(0, "Select Folder to Save Files:", 0).Self.Path
    On Error GoTo 0
    If Len(FolderPath) = 0 Then Exit Sub    'Pressed cancel

    CreateTxtFiles.CreateTxtFiles FolderPath & "\sample1.txt", 1, "sample1", "sample1_", 7, "sample1_2", 9

End Sub

答案 1 :(得分:0)

您可能正在寻找user sees minus the actual size of the content财产https://msdn.microsoft.com/en-us/vba/office-shared-vba/articles/filedialog-selecteditems-property-office

FileDialog.SelectedItems

希望这有帮助!

相关问题