Excel到.tsv文件,但仍然有逗号和引号

时间:2018-07-23 09:22:10

标签: vba excel-vba csv

我正在尝试通过运行以下代码来创建新的.tsv文件。但是,即使我将其设置为.tsv,输出也仍然位于.csv文件中。有什么办法解决这个问题?

Sub toTxt()
    Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
    myFile = Application.DefaultFilePath & "\PO" & Format(Now(), "yyyymmddhhmmss") & ".tsv"
    iLast = ThisWorkbook.Sheets("PO_Master").Range("C" & Rows.Count).End(xlUp).Row

    Set rng = ThisWorkbook.Sheets("PO_Master").Range("A7:BA" & iLast)
    Open myFile For Output As #2
    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 #2, cellValue
            Else
                Write #2, cellValue,
            End If
        Next j
    Next i

    Close #2

样本输出

ASA,"AA","BB","CC","DD","EE","FF"

1 个答案:

答案 0 :(得分:1)

尝试构建字符串outputline(您需要声明它),并且只在每个中写入数据。

For i = 1 To rng.Rows.Count
    outputline = ""
    For j = 1 To rng.Columns.Count
        cellValue = rng.Cells(i, j).Value

        If outputline = "" Then
            outputline = outputline & cellValue
        Else
            outputline = outputline & Chr(9) & cellValue
        End If

    Next j
    Print #2, outputline

Next i