【问题标题】:Create multiple text files using multiple Excel worksheets using VBA使用 VBA 使用多个 Excel 工作表创建多个文本文件
【发布时间】:2016-08-13 09:46:19
【问题描述】:

所以我要做的是从我的 excel 文件中的每个工作表创建一个文本文件,只导出列 D

到目前为止,我有一个导出列 D 的宏,但仅在活动工作表上。

这是我当前的宏:

 Private Sub CommandButton21_Click()

    Dim userName As Variant
    userName = InputBox("Enter your six character user ID")
    Dim userNamePath As String
    userNamePath = "C:\Users\" & userName & "\Desktop\Device Configurations\"
    MkDir userNamePath
    Dim filename As String, lineText As String
    Dim myrng As Range, i, j

    filename = userNamePath & "test.txt"

    Open filename For Output As #1

    Set myrng = Range("C1:C5, D1:D5")

    For i = 1 To myrng.Rows.Count

        For j = 1 To myrng.Columns.Count
            lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
        Next j
        Print #1, lineText
    Next i

    Close #1
End Sub

所以我在用户桌面上创建了一个名为“Device configurations”的文件夹,并将文本文件放入该目录。出于测试目的,该文本文件称为“test”。我想用它们各自工作表的名称导出这些文本文件。

例如,我想从每个工作表中导出工作表12345,但只有列D,并且每个工作表都需要有自己的文本文件。我想通过单击宏来完成此操作。

【问题讨论】:

    标签: excel vba export range worksheet


    【解决方案1】:

    如果我理解正确,您只需要在代码周围添加一个循环:

    Sub t()
    Dim ws      As Worksheet
    
    Dim userName As Variant
    userName = InputBox("Enter your six character user ID")
    Dim userNamePath As String
    userNamePath = "C:\Users\" & userName & "\Desktop\Device Configurations\"
    MkDir userNamePath
    Dim filename As String, lineText As String
    Dim myrng   As Range, i, j
    
    For Each ws In ActiveWorkbook.Sheets
        With ws
            filename = userNamePath & .Name & " - test.txt"    ' to add the worksheet name to the text file
    
            Open filename For Output As #1
    
            Set myrng = .Range("C1:C5, D1:D5")
    
            For i = 1 To myrng.Rows.Count
    
                For j = 1 To myrng.Columns.Count
                    lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
                Next j
                Print #1, lineText
            Next i
    
            Close #1
        End With                 'ws
    Next ws
    
    End Sub
    

    【讨论】:

    • BruceWayne 这是我一直在寻找的答案。我将更多地研究添加循环以供将来参考。感谢您的及时回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2018-07-14
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    相关资源
    最近更新 更多