将Excel工作簿中特定列的数据添加到文本文件

83qze16e  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(169)

我想知道在Excel VBA中是否有一种方法可以打开与工作簿具有相同文件路径的文本文件,从特定列或区域复制数据并将其粘贴到文本文件中。
我希望对一个有多个工作表的工作簿也这样做,所以我希望为每个工作表创建一个文本文件作为它们的名称,并从一列输入数据。
基本上,我需要做的是创建一个名为"sheet 1"的文本文件,并从工作表01的"A"列输入数据。然后创建一个名为"sheet 2"的文本文件,并从工作表02的"A"列输入数据。
如果我可以输入从范围"A3"到列"A"中数据结尾的数据,而不是输入整列的数据,那就更好了。
谢谢!
我试图将数据导出到文本文件,但它将整个工作表导出到文本文件。

rhfm7lfc

rhfm7lfc1#

将单列区域导出到文本文件

Sub ExportColumnsA()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim pSep As String: pSep = Application.PathSeparator
    Dim TextFile As Long: TextFile = FreeFile
    
    Dim ws As Worksheet, rg As Range, fCell As Range, lCell As Range
    Dim Data(), rCount As Long, r As Long, rString As String, fPath As String
    
    For Each ws In wb.Worksheets
        Set fCell = ws.Range("A3")
        Set lCell = fCell.Resize(ws.Rows.Count - fCell.Row + 1) _
            .Find("*", , xlFormulas, , , xlPrevious)
        If Not lCell Is Nothing Then ' data in column
            ' Reference the range.
            Set rg = ws.Range(fCell, lCell)
            ' Write the values from the range to an array.
            rCount = rg.Rows.Count
            If rCount = 1 Then
                ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
            Else
                Data = rg.Value
            End If
            ' Write the values from the array to a string.
            rString = CStr(Data(1, 1))
            For r = 2 To rCount
                rString = rString & vbLf & CStr(Data(r, 1))
            Next r
            ' Write the string to the text file.
            fPath = wb.Path & pSep & ws.Name & ".txt"
            Open fPath For Output As #TextFile
                Print #TextFile, rString;
            Close #TextFile
        'Else ' no data in column; do nothing
        End If
    Next ws
    
    MsgBox "Columns ""A"" exported.", vbInformation

End Sub

相关问题