将选定单元格的导出写为.txt文件,不带“引号”

时间:2017-03-23 17:38:32

标签: excel vba excel-vba export-to-csv

我正在制作一张获得大量信息的Excel表格。 有些列包含我需要在脚本中使用的信息,我使用以下代码来保存我在单击按钮后在.txt文件中选择的内容。

Private Sub CommandButton21_Click()
    Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
    myFile = Application.DefaultFilePath & "\NumeroChamados.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

事情就是我保存的所有内容都会带有引号,如下例所示:

"4146546546523133"
"4285725763131"
"461"
"4230236646435356694197285187451644148"
"4230375763756379653464564"

我选择的单元格通常包含来自另一个单元格的字符串,我在其中使用宏来获取它。

1 个答案:

答案 0 :(得分:3)

为了避免将包装引号添加到任何Excel解释为字符串(甚至是看起来像数字的文本),请使用Print而不是Write

Private Sub CommandButton1_Click()
    Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
    myFile = Application.DefaultFilePath & "\NumeroChamados.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
                Print #1, cellValue
            Else
                Print #1, cellValue,
            End If
        Next j
    Next i
    Close #1
End Sub

enter image description here