如何在VBA中创建文件夹并将txt文件放入其中

时间:2020-02-06 19:04:58

标签: excel vba

我编写了一个代码,然后问用户他想在哪里放置从excel工作表创建的文本文件。 如果选定的文件夹名为formatted file,则应创建一个文件。如果文件夹formatted file不存在,则代码应创建一个名为formatted Files的文件,然后在其中创建文本文件。 文本文件包含来自Excel的4列数据。 现在,该文件夹已创建在正确的位置。使用正确的解决方案更新代码。

如果有一种方法可以简化我的代码,请告诉我!

这是我的实际代码:

       Sub register_formated_data()
    '
    ' register_formated_data Macro
    '
    Dim order As Object
    Dim Folder As Object
    Dim Folder_path As String
    Dim lastrow As Long

    Dim fSo As Object
    Dim myFile As Object

    FolderName = "Formated Files"
    Filename = "formated" & Right(Sheets(8).Cells(12, 6).Value, InStr(File_path, "\"))

    Dim FL As String ' FL is for file location

    Sheets(8).Cells(12, 12).Value = ""

    With Application.FileDialog(msoFileDialogFolderPicker)   '
        .Title = "Select where you want the folder to be"  'Open the file explorer
        .InitialFileName = ThisWorkbook.path & "\"         'for you to select
        .InitialView = msoFileDialogViewDetails            'the file you want
        .AllowMultiSelect = True                           'to add the txt file
        .Show                                              '

        On Error GoTo PROC_EXIT
        If Not .SelectedItems(1) = vbNullString Then FL = .SelectedItems(1)

    End With

    Sheets(8).Cells(12, 12).Value = FL

    Folder_path = FL + "\" + FolderName

Set fSo = CreateObject("Scripting.FileSystemObject")
If Not fSo.FolderExists(Folder_path) Then
    fSo.CreateFolder (Folder_path)
    If fSo.FolderExists(Folder_path) Then
        Set fSo = CreateObject("Scripting.FileSystemObject")
        Set myFile = fSo.CreateTextFile(Folder_path + "\" + Filename, True)

        myFile.WriteLine "Error"

        myFile.Close
        Set fSo = Nothing
    End If
Else
    If fSo.FolderExists(Folder_path) Then
    Set fSo = CreateObject("Scripting.FileSystemObject")
    Set myFile = fSo.CreateTextFile(Folder_path + "\" + Filename, True)

    myFile.WriteLine "Error"

    myFile.Close
    Set fSo = Nothing
    End If
End If


PROC_EXIT:
End Sub

1 个答案:

答案 0 :(得分:1)

使用FileDialog选择FL时,似乎您正在尝试创建已存在的文件夹FL。

使用 fSo.CreateFolder(FL).Name = FolderName 等同于

folder = fSo.CreateFolder(FL) folder.Name = FolderName

因此,您需要用fSo.CreateFolder(FolderName)代替它。

校正后的代码块如下:

Set fSo = CreateObject("Scripting.FileSystemObject")
If Not fSo.FolderExists(Folder_path) Then
    fSo.CreateFolder(Folder_path)          
    If fSo.FolderExists(Folder_path) Then
        Set fSo = CreateObject("Scripting.FileSystemObject")
        Set myFile = fSo.CreateTextFile(Folder_path + "\" + Filename, True)

        myFile.WriteLine "Error"

        myFile.Close
        Set fSo = Nothing
    End If
End If