导出时 Excel VBA 在文本文件末尾放置额外的空行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4017968/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:14:10  来源:igfitidea点击:

Excel VBA puts extra blank line at end of text file when exporting

excelvbatextexcel-vba

提问by Shawn H

I have an Excel VBA macro that outputs to a text file. There is always a blank row at the bottom of the text file and I am having trouble getting rid of it. Any useful suggestions would be greatly appreciated! Thanks

我有一个输出到文本文件的 Excel VBA 宏。文本文件底部总是有一个空白行,我无法摆脱它。任何有用的建议将不胜感激!谢谢

Sub testExport()

  Dim fPath As String, exportTxt As String
  fPath = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\Sample_" & Format(Now(), "HHNNSS") & ".txt"

  exportTxt = "Project: Sample Output" & vbCrLf
  exportTxt = exportTxt & "Model Version: 1 "


  Open fPath For Append As #1    'write the new file
  Print #1, exportTxt
  Close #1

End Sub

结束子

采纳答案by barrowc

From the help on the Print #statement and ways to specify charposafter the data has been output:

Print #语句的帮助和charpos数据输出后的指定方式来看:

charposSpecifies the insertion point for the next character. Use a semicolon to position the insertion point immediately after the last character displayed. Use Tab(n) to position the insertion point to an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

charpos指定下一个字符的插入点。使用分号将插入点紧跟在显示的最后一个字符之后。使用 Tab(n) 将插入点定位到绝对列号。使用不带参数的 Tab 将插入点定位在下一个打印区域的开头。如果省略 charpos,则在下一行打印下一个字符。

Try the following instead:

请尝试以下操作:

Print #1, exportTxt;

回答by Steas

What I did and worked was, after I created the txt file, counted the lines with data I wanted to be copied, and then loop through it creating a new file using the Print #1, exportTxt; and also Print #1, "", except in the last row.

我所做的工作是,在创建 txt 文件后,计算要复制的数据的行数,然后使用 Print #1, exportTxt 循环创建一个新文件;以及打印 #1, "",除了最后一行。

Open sOrgFile For Input As #1
Do While Not EOF(1)
iCounter = iCounter + 1
Line Input #1, sData
If sData = "" Then Exit Do
Loop
Close #1

Open sOrgFile For Input As #1
Open sDestFile For Output As #2
Do While Not EOF(1)
iCounter2 = iCounter2 + 1
Line Input #1, sData
    If sData = "" Then Exit Do
Print #2, sData;
If iCounter2 <> iCounter Then Print #2, ""
sData = ""
Loop

回答by dilshan

Print #1, exportTxt;

it prints everything in one line. no line break at all.

它在一行中打印所有内容。根本没有换行。