【问题标题】:How to Output multiple text files based on column name?如何根据列名输出多个文本文件?
【发布时间】:2018-05-19 12:35:56
【问题描述】:

我有一个格式如下的 Excel 电子表格。

Excel File

第1栏:AAA BBB AAA BBB DDD BBB CCC BBB CCC

第2栏:狐虎猴鸟猫狼狗鱼猪

我想将它们保存到多个文本文件中,使用第 1 列作为文件名----“AAA”、“BBB”、“CCC”、“DDD”。内容应该是第 2 列。每个文本文件应该有多行。

例如,在文本文件“AAA”中,内容应该是:

狐狸 猴子

我现在正在使用以下 VBA 脚本。但是对于每个文本文件,我只能生成一行。

Sub Export_Files()
Dim sExportFolder, sFN
Dim rArticleName As Range
Dim rDisclaimer As Range
Dim oSh As Worksheet
Dim oFS As Object
Dim oTxt As Object

'sExportFolder = path to the folder you want to export to
'oSh = The sheet where your data is stored
sExportFolder = "I:\Projects\2017\Two_Weeks_Vacations\2017\December\Test\EmployeesOnVacation"
Set oSh = Sheet1

Set oFS = CreateObject("Scripting.Filesystemobject")

For Each rArticleName In oSh.UsedRange.Columns("A").Cells
    Set rDisclaimer = rArticleName.Offset(, 1)

    'Add .txt to the article name as a file name
    sFN = rArticleName.Value & ".txt"
    Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & sFN, 2, True)
    oTxt.Write rDisclaimer.Value
    oTxt.Close
Next
End Sub

【问题讨论】:

  • 您能否对列进行排序,使 AAA、BBB、AAA 变为 AAA、AAA、BBB?如果是这样,您可以快速循环遍历每个单元格,否则会变得有点复杂。
  • 谢谢。是的,我可以对数据进行排序,但不确定如何将循环添加到脚本中。

标签: vba excel text spreadsheet


【解决方案1】:

如果可以排序,则可以使用基本模板:

Public a as String

Sub 
    Dim i as Long, lr as Long, strO as String, strN as String
    LR = Cells(Rows.Count, 1).End(xlUp).Row
    For i = i to lr Step 1
        strO = a
        If Cells(i,1).Value = Cells(i-1,1).Value Then
            If a <> "" Then Export_Files 'Calls the Sub that names the file... or you can just name and do that stuff here.
            a = ""
            strO = Cells(i,2).Value
        Else
            strN = Cells(i,2).Value
        End If
        a = strO & " " & strN
    Next i
    Export_Files
    a = ""
End Sub

然后需要修复 Export_Files 宏的命名,在其中删除选择文件名的部分并更改总文件保存名称:

Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & a, 2, True)

【讨论】:

  • 感谢您回复我的问题。我会努力的!
猜你喜欢
  • 1970-01-01
  • 2012-08-08
  • 2019-11-08
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 2021-03-20
相关资源
最近更新 更多