用于将Excel 2007工作表转换为制表符分隔文本文件的VBA代码

时间:2014-04-29 17:29:29

标签: excel vba text

我找到了将Excel工作表转换为文本文件的代码。如何修改它以创建制表符分隔的文本文件?我不是VB程序员,所以如果你将代码插入它所属的位置会有所帮助。

提前致谢!

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
        For c = FirstCol To LastCol
             '  data = ExpRng.Cells(r, c).Value
            Data = Data & " " & ExpRng.Cells(r, c).Value
            If c = LastCol Then
                Print #1, Data
                Data = ""
            End If
        Next c
    Next r
    Close #1
End Sub

2 个答案:

答案 0 :(得分:1)

没有测试:

替换:

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

使用:

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

答案 1 :(得分:0)

可以缩短并加速如下:

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