将 Excel 2007 工作表转换为制表符分隔的文本文件的 VBA 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23371424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA code to convert Excel 2007 sheet to tab-delimited text file
提问by user3586303
I found this code for converting an Excel sheet to a text file. How can I modify it to create a tab-delimited text file? I am not a VB programmer, so it would help if you insert the code where it belongs.
我找到了将 Excel 工作表转换为文本文件的代码。如何修改它以创建制表符分隔的文本文件?我不是 VB 程序员,所以如果你在它所属的地方插入代码会有所帮助。
Thanks in advance!
提前致谢!
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
回答by Gary's Student
Without testing:
未经测试:
Replace:
代替:
Data = Data & " " & ExpRng.Cells(r, c).Value
with:
和:
Data = Data & vbTab & ExpRng.Cells(r, c).Value
回答by Chuck
Can be shortened and sped up as follows:
可以缩短和加速如下:
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