vba excel转txt
时间: 2023-10-09 08:12:28 浏览: 82
你可以使用 VBA 代码将 Excel 文件转换为文本文件。以下是一个示例代码:
```vb
Sub ExportToTextFile()
Dim myFile As String
Dim rng As Range
Dim cellValue As Variant
Dim i As Integer, j As Integer
'Get file name
myFile = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
'Exit if user cancels
If myFile = "" Then Exit Sub
'Open file for output
Open myFile For Output As #1
'Loop through each row and column in the range
For i = 1 To ActiveSheet.UsedRange.Rows.Count
For j = 1 To ActiveSheet.UsedRange.Columns.Count
'Get cell value
cellValue = ActiveSheet.Cells(i, j).Value
'Write cell value to file
If j = ActiveSheet.UsedRange.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,
End If
Next j
Next i
'Close file
Close #1
MsgBox "Export complete."
End Sub
```
在运行代码之前,请确保你已经保存了 Excel 文件。该代码将提示你选择一个文本文件的保存位置。然后,它将循环遍历所选范围中的每个单元格,并将其值写入文本文件中。
阅读全文