【问题标题】:Specifying new folder for .txt path in Excel在 Excel 中为 .txt 路径指定新文件夹
【发布时间】:2021-06-07 04:04:23
【问题描述】:

我正在尝试使用 VBA 创建名为 [Cell Value 1] 的文件夹,然后在这些文件夹中创建名为 [Cell Value 1]&[Cell Value 2] 且内容为 [Cell Value 3] 的文本文件。

我已经编写了一个工作代码来使 .txt 文件命名并包含内容,但我不知道如何为要存储的 .txt 文件创建文件夹。

示例表

Last Name First Name Birthday
Smith John 1/2/1980
Pearson Sam 5/4/1974
Smith Jane 12/5/1962

我当前的输出是 John Smith txt,内容为 1/2/1980 Sam Pearson.txt,内容为 1974 年 5 月 4 日 Jane Smith.txt,内容为 1962 年 12 月 5 日

我希望这些按姓氏分类到文件夹中,因此输出应该是 文件夹:史密斯与内容约翰史密斯 txt 和简史密斯 txt 文件夹:Pearson 与内容 Sam Pearson txt

这是我目前的代码

Sub create_Txt()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object

Dim i&, lastRow&
lastRow = Cells(Rows.Count, 1).End(xlUp).Row

For i = 1 To lastRow
    Set oFile = fso.CreateTextFile("C:\Users\mason\Desktop\" & Cells(i, 3) & " " & Cells(i, 2) 
    & ".txt")
    oFile.WriteLine Cells(i, 4).Value
    oFile.Close 
Next i
Set fso = Nothing
Set oFile = Nothing
End Sub

谢谢!

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    试试这个代码:

    Option Explicit
    
    Sub create_Txt()
        Const BASE_PATH = "c:\temp\test\" ' "C:\Users\mason\Desktop\"
        ' It is more convenient to work with objects using early binding. Subsequently can be changed to late binding if needed
        ' set reference to 'Microsoft Scripting Runtime'
        Dim fso As FileSystemObject, oFolder As Scripting.Folder, oFile As Scripting.TextStream
        Set fso = New FileSystemObject  ' CreateObject("Scripting.FileSystemObject")
        
        Dim i As Long, lastRow As Long, path As String
        
        With ThisWorkbook.Sheets(1)   'replace with your own 
            lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
            
            For i = 2 To lastRow    'start from 2 - skip header
                path = BASE_PATH & .Cells(i, 1)                             'append path with lastname
                If Not fso.FolderExists(path) Then fso.CreateFolder path    'make folder
                Set oFile = fso.CreateTextFile(path & "\" & .Cells(i, 2) & " " & .Cells(i, 1) & ".txt")
                oFile.WriteLine .Cells(i, 3).Value
                oFile.Close
            Next i
        End With
    End Sub
    

    数据

    结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-18
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多