【问题标题】:Export Excel-Cells to TXT file with defined length将 Excel 单元格导出到具有定义长度的 TXT 文件
【发布时间】:2016-06-03 14:19:36
【问题描述】:

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

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

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

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

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

所以TXT文件应该是这样的:

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

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

【问题讨论】:

  • 您可能想查看以下 VBA 代码:stackoverflow.com/questions/35434220/…。它正在处理基于文本的文件并对其进行编辑。以此为起点,您应该很容易弄清楚其余部分(鉴于您之前使用过 Excel marcos)。

标签: excel vba


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多