Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

text

excel

vba

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

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

like image 841
Shawn H Avatar asked Oct 25 '10 19:10

Shawn H


2 Answers

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

charpos Specifies 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.

Try the following instead:

Print #1, exportTxt;
like image 108
barrowc Avatar answered Sep 22 '22 07:09

barrowc


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.

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
like image 27
Steas Avatar answered Sep 18 '22 07:09

Steas