如何将Excel数据(选择或工作表)导出到文本文件
要在 Excel 中将 Excel 数据导出到文本文件,您可以使用 VBA 宏。通过几个简单的步骤,您可以创建一个宏,将选定的范围或整个工作表导出到文本文件。该宏将单元格中的数据转换为文本格式,循环遍历每个单元格并构建文本数据。然后,它会提示用户选择保存文本文件的文件名和位置。保存后,会显示一条消息以确认导出成功。使用此方法,您可以轻松地将 Excel 数据导出到文本文件,以供进一步分析或共享。
将 Excel 数据导出到文本文件的步骤
以下是如何操作的步骤
步骤 1
打开您想要将 Excel 数据导出到文本文件的 Excel 文件。
按 Alt + F11 在 Excel 中打开 Visual Basic 编辑器。
通过单击“插入”并选择“模块”来插入一个新模块。
在模块窗口中,粘贴以下代码
Sub ExportToTextFile()
Dim SaveFileName As Variant
Dim FilePath As String
Dim TextData As String
Dim SelectedRange As Range
' Set the default file name and path
SaveFileName = Application.GetSaveAsFilename(InitialFileName:="ExportedData",
FileFilter:="Text Files (*.txt), *.txt")
' Check if user canceled the save dialog
If SaveFileName = False Then Exit Sub
' Get the selected range or entire active sheet
On Error Resume Next
Set SelectedRange = Selection.SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If SelectedRange Is Nothing Then
Set SelectedRange = ActiveSheet.UsedRange
End If
' Loop through each cell in the range and build the text data
For Each Cell In SelectedRange
TextData = TextData & Cell.Value & vbTab
Next Cell
' Remove the last tab character
TextData = Left(TextData, Len(TextData) - 1)
' Get the file path from the save file name
FilePath = Left(SaveFileName, InStrRev(SaveFileName, ""))
' Create a new text file and write the data
Open SaveFileName For Output As #1
Print #1, TextData
Close #1
' Show a message when the export is completed
MsgBox "Data exported to " & SaveFileName, vbInformation
End Sub

步骤 2
保存模块并关闭 VBA 编辑器。
现在,您可以使用宏将数据导出到文本文件。
选择要导出的单元格范围,或确保活动工作表包含要导出的数据。
步骤 3
按“Alt + F8”打开宏对话框。
从列表中选择“ExportToTextFile”宏,然后单击“运行”。

步骤 4
选择一个文件名和位置来保存文本文件。

结论
要在 Excel 中将 Excel 数据导出到文本文件,您可以使用 VBA 宏。通过将提供的代码插入 VBA 编辑器中的模块中,您可以创建一个名为“ExportToTextFile”的宏。此宏允许您选择一个范围或将整个活动工作表导出到文本文件。运行宏后,保存对话框会提示您为文本文件选择文件名和位置。然后循环遍历所选数据并将其写入文本文件。最后,一个消息框确认导出成功。此方法提供了一种便捷的方式,可以将 Excel 数据导出到文本文件以供进一步使用或分析。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP