将Excel-Cells导出为定义长度的TXT文件

时间:2016-06-02 16:07:29

标签: excel-vba vba excel

我有一个Excel文件,如下所示:

http://i.stack.imgur.com/AMi3c.jpg

(抱歉没有嵌入图片,但我暂时不允许这样做,因为我刚刚在这里注册)

我想将其导出到TXT文件,其中给出了每列的字符数。

例如: A列中的每个单元格在我的文本文件中应该只有3个字符,B列应该有5个。如果我的单元格不包含确切的字符数,那么TXT文件应该填充空格。

因此TXT文件应如下所示:

http://i.stack.imgur.com/5U7AM.jpg

之前我曾使用Excel Macros,但我不确定如何开始使用这个。感谢您的帮助,非常感谢

1 个答案:

答案 0 :(得分:1)

这是对我有用的代码:

Sub Export_File()

Dim myFile As String, r As Integer, mypath As String, dline As String

mypath = "C:\RESULTS\" 'path for file
myFile = "file.txt" 'file name
dline = ""

For r = 2 To Range("A" & Rows.Count).End(xlUp).Row

A = Cells(r, "A") & Application.WorksheetFunction.Rept(" ", 3 - Len(Cells(r, "A")))
B = Cells(r, "B") & Application.WorksheetFunction.Rept(" ", 5 - Len(Cells(r, "B")))
C = Cells(r, "C") & Application.WorksheetFunction.Rept(" ", 5 - Len(Cells(r, "C")))
D = Cells(r, "D") & Application.WorksheetFunction.Rept(" ", 5 - Len(Cells(r, "D")))
E = Cells(r, "E") & Application.WorksheetFunction.Rept(" ", 7 - Len(Cells(r, "E")))
F = Cells(r, "F") & Application.WorksheetFunction.Rept(" ", 7 - Len(Cells(r, "F")))
G = Cells(r, "G") & Application.WorksheetFunction.Rept(" ", 5 - Len(Cells(r, "G")))
H = Cells(r, "H") & Application.WorksheetFunction.Rept(" ", 5 - Len(Cells(r, "H")))
I = Cells(r, "I") & Application.WorksheetFunction.Rept(" ", 5 - Len(Cells(r, "I")))


dline = dline & A & B & C & D & E & F & G & H & I & vbLf & vbCr

Next r

Open mypath & myFile For Output As #1 'Replaces existing file
Print #1, dline
Close #1

MsgBox ("File Created " & mypath & myFile)


End Sub