【问题标题】:How can I improve my export from Excel selection to text file?如何改进从 Excel 选择到文本文件的导出?
【发布时间】:2019-09-03 19:27:25
【问题描述】:

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

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    首先,标题可以很容易地通过获取单元格值来检索。假设它将与您选择的顶部在同一行,但右侧有 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多