VBA代码将Excel工作表保存为制表符分隔的文本文件

时间:2017-04-27 10:33:54

标签: excel-vba vba excel

我找到了这段代码并试了一下。它工作正常,但在保存的文本文件中,第一列有空格(对于所有行)。我无法修复此代码。请帮忙。

Sub ExportRange()
Dim ExpRng As Range
Open ThisWorkbook.Path & "\AllDXL.txt" For Output As #1
Set ExpRng = Worksheets("Sheet1").Range("A1").CurrentRegion
FirstCol = ExpRng.Columns(1).Column
LastCol = FirstCol + ExpRng.Columns.Count - 1
FirstRow = ExpRng.Rows(1).Row
LastRow = FirstRow + ExpRng.Rows.Count - 1
For r = FirstRow To LastRow
 Data = ""
 For c = FirstCol To LastCol
  '  data = ExpRng.Cells(r, c).Value
  Data = Data & vbTab & ExpRng.Cells(r, c).Value
Next c
Print #1, Data
Next r
Close #1
End Sub

3 个答案:

答案 0 :(得分:1)

您为每个单元格添加vbTab作为前缀,包括第一个单元格。更改以下内容:

Data = Data & vbTab & ExpRng.Cells(r, c).Value

If c = FirstCol Then
    Data = Data & ExpRng.Cells(r, c).Value
Else
    Data = Data & vbTab & ExpRng.Cells(r, c).Value
End If

或者,如果每一行总会有一些数据,您可以在vbTab阶段从第一行中删除第一个Print

更改

Print #1, Data

Print #1, Mid(Data, 2, Len(Data)-1)

答案 1 :(得分:1)

这也有效......

Sub ExportRange()
Dim ExpRng As Range
Dim myTab As String
Open ThisWorkbook.Path & "\AllDXL.txt" For Output As #1
    Set ExpRng = Worksheets("Sheet1").Range("A1").CurrentRegion
    FirstCol = ExpRng.Columns(1).Column
    LastCol = FirstCol + ExpRng.Columns.Count - 1
    FirstRow = ExpRng.Rows(1).Row
    LastRow = FirstRow + ExpRng.Rows.Count - 1
    For r = FirstRow To LastRow
       Data = ""
       For c = FirstCol To LastCol
           If c = 1 Then myTab = "" Else myTab = vbTab
        '  data = ExpRng.Cells(r, c).Value
           Data = Data & myTab & ExpRng.Cells(r, c).Value
       Next c
       Print #1, Data
   Next r
Close #1
End Sub

答案 2 :(得分:1)

希望这可以为某人节省一些时间:

Sub ExportToTxt()
    Dim fileStream As Object
    Set fileStream = CreateObject("ADODB.Stream")
    fileStream.Charset = "utf-8"
    fileStream.Open

    Dim rangeToExport As Range
    Set rangeToExport = Worksheets("BPC-Processed").Range("A1").CurrentRegion

    Dim firstCol, lastCol, firstRow, lastRow As Integer
    firstCol = rangeToExport.Columns(1).Column
    lastCol = firstCol + rangeToExport.Columns.Count - 1
    firstRow = rangeToExport.Rows(1).row
    lastRow = firstRow + rangeToExport.Rows.Count - 1

    Dim r, c As Integer
    Dim str, delimiter As String
    For r = firstRow To lastRow
        str = ""
        For c = firstCol To lastCol
            If c = 1 Then
                delimiter = ""
            Else
                delimiter = vbTab ' tab
            End If
            str = str & delimiter & rangeToExport.Cells(r, c).Value
        Next c
        fileStream.WriteText str & vbCrLf ' vbCrLf: linebreak
    Next r

    Dim filePath As String
    filePath = Application.ThisWorkbook.Path & "\BPC-Processed.txt"
    fileStream.SaveToFile filePath, 2 ' 2: Create Or Update
    fileStream.Close
End Sub