2017-10-17 127 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

相關問題