首页 > 解决方案 > 如何改进从 Excel 选择到文本文件的导出?

问题描述

我正在尝试将 Excel 数据导出到单个文本文件。目前,我下面的代码将 Excel 中的选择导出到名为“AgreementText.txt”的文件中。我想做两件事来改进它,但我不确定如何:

首先,我想为每个 .txt 文件命名不同的名称。文件的标题列在每个选择左侧的第 4 列中。有什么方法可以让我每次都从该列中获取标题?

其次,文本当前出现在文本文件中,并带有引号。有什么办法可以删除这些吗?

编辑:第三,我还需要为默认指定不同的文件路径,但我不确定如何。

提前致谢!

Sub TextFileExport()
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
myFile = Application.DefaultFilePath & "\AgreementText.txt"
Set rng = Selection
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
    For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
    Write #1, cellValue
Else
    Write #1, cellValue,
End If
 Next j
Next i
Close #1
End Sub

标签: excelvba

解决方案


首先,标题可以很容易地通过获取单元格值来检索。假设它将与您选择的顶部在同一行,但右侧有 4 列,您可以按以下方式进行操作:

myFile = Application.DefaultFilePath & "\" & Selection.Cells(1, Selection.Columns.Count + 4) & ".txt"
Open myFile For Output As #1

其次,您可以使用Print而不是Write不带引号的打印。我发现最简单的方法是将要编写的整行构建为一个字符串,然后Print为每一行执行一个命令。

把它们放在一起:

Sub TextFileExport()
    Dim myFile As String
    Dim rng As Range
    Dim line
    Dim i As Integer
    Dim j As Integer
    Set rng = Selection
    myFile = Application.DefaultFilePath & "\" & rng.Cells(1, rng.Columns.Count + 4) & ".txt"
    Open myFile For Output As #1
    For i = 1 To rng.Rows.Count
        line = ""
        For j = 1 To rng.Columns.Count
            line = line & rng.Cells(i, j).Value
            If j < rng.Columns.Count Then
                line = line & ","
            End If
        Next
        Print #1, line
    Next
    Close #1
End Sub

推荐阅读