如何改善从Excel选择到文本文件的导出?

时间:2019-09-03 10:47:57

标签: excel vba

我正在尝试将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

1 个答案:

答案 0 :(得分:0)

首先,只需获取单元格值即可轻松检索标题。假设它与所选内容位于同一行,但在右边四列中,则可以执行以下操作:

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