首页 文章

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

提问于
浏览
0

我创建了一个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

结束子

2 回答

  • 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

    你可能在寻找 FileDialog.SelectedItems Property 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
    

    希望这可以帮助!

相关问题