编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

利用VBA将Excel工作表导出为文本文件

wxchong 2025-03-20 20:17:33 开源技术 3 ℃ 0 评论

引言

将Excel工作表导出为文本文件是一种常见的需求,它允许数据以一种简单、通用的格式被保存和共享。常用的导出方法有以下两种:(1)直接复制黏贴。选中Excel工作表区域,并复制黏贴到文本文件。此时,行单元格之间以Tab键分割开;(2)使用Excel自带的“另存为”功能。另存为“CSV (逗号分隔)”的文本文件格式。顾名思义,行单元格之间以逗号分割开。

这两种导出方法虽然可以满足一定的需求,但还有一定的局限性。因此,我们可以利用VBA,以应对一些更复杂、更多样的导出场景:(1)行单元格之间的分隔符提供了更大的弹性,可以使用逗号、Tab键、甚至是任何字符;(2)实现将Excel工作表导出为文本文件的全流程自动化

实现思路

1.创建文本文件;

2.将工作表每一行的数据,用连接符拼接起来;

3.将拼接后的每一行数据写入文本文件。

VBA代码

Sub 导出Excel为文本文件()
    '创建FileSystemObject对象
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    ' 指定文件路径和名称
    Dim filePath As String
    filePath = "C:\Users\VBAMatrix\Desktop\newfile.txt"

    ' 创建新文本文件,参数为True,即文件存在则覆盖
    Dim file As Object
    Set file = fso.CreateTextFile(filePath, True)
    
    Dim fistRow As Integer, lastRow As Integer
    firstRow = ActiveSheet.UsedRange.Row
    lastRow = firstRow + ActiveSheet.UsedRange.Rows.Count - 1
    
    Dim firstColumn As Integer, lastColumn As Integer
    firstColumn = ActiveSheet.UsedRange.Column
    lastColumn = firstColumn + ActiveSheet.UsedRange.Columns.Count - 1

    Dim i As Integer, j As Integer
    Dim txtwd As String
    '循环遍历当前工作表的每一行
    For i = firstRow To lastRow
        txtwd = ""
        For j = firstColumn To lastColumn
            '行区域的单元格之间以逗号进行分割
            txtwd = txtwd & ActiveSheet.Cells(i, j).Value & ","
        Next
        '将连接后的行数据,写入文本文件中
        file.WriteLine (Left(txtwd, Len(txtwd) - 1))
    Next

    ' 关闭文件
    file.Close
    
    '释放资源
    Set file = Nothing
    Set fso = Nothing
End Sub

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表