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

我创build了一个VBA代码,我生成文本文件。 我将7个parameter passing给一个子方法来生成所有的文本文件。 但是,我很难将生成的文件保存到用户select的文件夹中。 当我运行代码时,它只是将所有文件保存到包含的path中(因为我不知道如何执行上面解释的内容)。

下面是我的代码,我试图合并我可以用来让任何用户select一个文件夹保存所有生成的文本文件的path。

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 

结束小组

像这样的东西应该为你工作:

 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 

您可能正在寻找FileDialog.SelectedItems属性https://msdn.microsoft.com/en-us/vba/office-shared-vba/articles/filedialog-selecteditems-property-office

 Sub TextFiles() Dim MyFolder As FileDialog Dim Path As Variant Set MyFolder = Application.FileDialog(msoFileDialogFolderPicker) With MyFolder .AllowMultiSelect = False If .Show = -1 Then Path = .SelectedItems(1) Else End If End With '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 

希望这可以帮助!