2017-10-17 38 views
0

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

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

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 

末次

+0

“*我有困难... *”有什么困难?当你尝试时会发生什么?你有错误吗?它是否进入错误的文件夹?请具体以便我们帮助您。 – freginold

+0

@freginold,请参阅修改。谢谢 – Jesus

回答

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 
+0

你摇滚!这正是我所期待的。谢谢! :) – Jesus

0

你可能会寻找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 

希望这有助于!

+0

谢谢,这工作太:) – Jesus

相关问题