Excel 如何在VBA中创建文件夹并将txt文件放入其中
我编写了一个代码,然后询问用户,他想把从excel工作表创建的文本文件放在哪里。 如果所选文件夹名为Excel 如何在VBA中创建文件夹并将txt文件放入其中,excel,vba,Excel,Vba,我编写了一个代码,然后询问用户,他想把从excel工作表创建的文本文件放在哪里。 如果所选文件夹名为格式化文件,则应创建一个文件。如果文件夹格式化文件不存在,则代码应创建名为格式化文件的文件,然后在其中创建文本文件。 文本文件包含excel中的4列数据。 目前,文件夹是在正确的位置创建的。使用正确的解决方案更新代码 如果有办法简化我的代码,请告诉我 这是我的实际代码: Sub register_formated_data() ' ' register_formate
格式化文件
,则应创建一个文件。如果文件夹格式化文件
不存在,则代码应创建名为格式化文件
的文件,然后在其中创建文本文件。
文本文件包含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
由于使用文件对话框选择了
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
在出现错误时关闭线路
,转到PROC\u EXIT
,然后运行。您得到的具体错误是什么?@urdearboyi得到错误'58'文件夹已经存在。。。但我看不出来。。。msgbox FL给了我一个字符串,文件应该被替换的位置fso.CreateFolder(FL).Name=FolderName
byfso.CreateFolder(FolderName)
。结果是创建了文件夹(yay),但它不在好的文件夹中。(即,它应该在./folderA/folderB/格式化文件中,但在./folderA/formatted文件中)