如何在 Excel 中将每一行导出或保存为文本文件
Excel 是微软开发的一款强大的电子表格程序。它广泛用于各个行业和职业中组织、分析和处理数据。要将 Excel 中的多个列导出到各个文本文件中,可以使用 VBA(Visual Basic for Applications)宏。
在 Excel 中将每一行导出或保存为文本文件的步骤
以下是如何操作的示例
步骤 1:打开您想要将行导出为文本文件的 Excel 文件。按 Alt + F11 在 Excel 中打开 Visual Basic 编辑器。
通过点击“插入”并选择“模块”插入一个新的模块。在模块窗口中,粘贴以下代码
示例
Sub ExportRowsAsTextFiles() Dim ws As Worksheet Dim lastRow As Long Dim rowNum As Long Dim rowRange As Range Dim cellValue As String Dim filePath As String Dim cell As Range Set ws = ThisWorkbook.ActiveSheet ' Change to the appropriate sheet if needed lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row ' Assumes data starts in column A ' Loop through each row For rowNum = 1 To lastRow ' Set the range for the current row Set rowRange = ws.Range("A" & rowNum & ":" & ws.Cells(rowNum, ws.Columns.Count).End(xlToLeft).Address) ' Initialize cellValue as an empty string cellValue = "" ' Loop through each cell in the row For Each cell In rowRange ' Check the data type of the cell value Select Case True Case IsNumeric(cell.Value) ' Numeric value cellValue = cellValue & CStr(cell.Value) & "," Case IsDate(cell.Value) ' Date value cellValue = cellValue & Format(cell.Value, "dd-mm-yyyy") & "," Case Else ' Text value or other types cellValue = cellValue & CStr(cell.Value) & "," End Select Next cell ' Remove the trailing comma cellValue = Left(cellValue, Len(cellValue) - 1) ' Define the file path for the text file (change as needed) filePath = "E:\Assignments\3rd Assignments\How to export or save each row as text file in Excel\Output\file_" & rowNum & ".txt" ' Export the row as a text file Open filePath For Output As #1 Print #1, cellValue Close #1 Next rowNum MsgBox "Rows exported to individual text files." End Sub

步骤 2:根据需要修改代码:
将“ws”变量设置为要从中导出行的工作表。默认情况下,它从活动工作表导出。
调整 ws.Range("A" & rowNum & ":" & ws.Cells(rowNum, ws.Columns.Count).End(xlToLeft).Address) 中的列引用以匹配您想要导出的列范围。
将 filePath 变量更新到您想要保存文本文件的目标路径。示例代码将它们保存为 file_1.txt、file_2.txt 等文件名,在我的文件夹中。确保将路径更改为有效的目录。
步骤 3:按 Alt + F8 运行宏,选择“ExportRowsAsTextFiles”,然后点击“运行”。
代码将遍历指定工作表中的每一行,将该行中的值连接成一个逗号分隔的字符串,并将其保存为具有指定文件路径的文本文件。每一行都将拥有自己的文本文件。
结论
要将 Excel 文件中的每一行导出为单独的文本文件,您可以使用 VBA(Visual Basic for Applications)代码。代码遍历指定工作表的每一行,将该行中的值连接成一个逗号分隔的字符串。然后,该字符串将保存为具有唯一文件路径的文本文件,每个文件对应一行。
代码包括错误处理,以处理行中的不同数据类型。它检查一个值是否为数字、日期或属于“其他”类别,后者涵盖文本和其他类型。应用适当的转换,并将值追加到 cellValue 变量。生成的字符串使用指定的文件路径保存为文本文件。此过程确保 Excel 文件中的每一行都导出为单独的文本文件,以便在 Excel 之外进行进一步分析或处理。