11

With Visual Basic, I'm confused with that the behavior of Print statement in that sometimes the following statement: would cause additional carriage return "^M" at the end of a line, but sometimes, it doesn't. I wondering why?

filePath = "d:\tmp\FAE-IMM-Report-2012-Week.org"
    If Dir(filePath) <> "" Then
        Kill filePath
    End If
    outFile = FreeFile()
    Open filePath For Output As outFile
    Print #outFile, "#+TITLE:     Weekly Report"

would produce

#+TITLE:     Weekly Report^M

while I wish without ^M:

#+TITLE:     Weekly Report

In one test program, almost the same code would produce no "^M".

Please help! Thanks a lot.

Upon further experiment, I found that the following suggestion using vbNewline and ";" at the end of print content, still does not solve my problem.

After careful isolation, I found the cause of the problem is an character that seems like a space, not exactly space, followed by newline and carriage return. Before printing the text containing the offending string, there was no carriage return, but once the offending line is printed, then every line including the previous line printed would have carriage return.

I'm not sure what the exact the offending string is as my skill of VBA is not yet too well.

Here is a copy of the offending text from a spreadsheet cell:

   "There is something invisible after this visible text 
After the invisible text, then there might be a carriage return $Chr(13) and/or newline"

I'm not sure if the paste to web browser would preserve the content, though. By pasting to emacs, I did not see carriage return, while emacs should display it, if there is one. So I guess that there is no carriage return in the offending string.

Below is the program demonstrate the problem:

    Sub DemoCarriageReturnWillAppear()
    Dim filePath As String
    Dim outFile
    Dim offendingText
    filePath = "d:\tmp\demoCarriageReturn.org"
    If Dir(filePath) <> "" Then
        Kill filePath
    End If
    outFile = FreeFile()
    Open filePath For Output As outFile
    Print #outFile, "#+AUTHOR:    Yu Shen" & vbNewLine;
    Close #outFile 'At this moment, there is no carriage return
    Open filePath For Append As outFile
    offendingText = ThisWorkbook.Worksheets("Sheet1").Range("A1")
    Print #outFile, offendingText & vbNewLine;
    Close #outFile 'Now, every line end has carriage return.
    'It must be caused by something offending at the above print out content.
End Sub

Here is the final result of the above procedure:

    #+AUTHOR:    Yu Shen^M

There is something invisible after this visible text 
After the invisible text, then there might be a carriage return $Chr(13) or newline^M

Note the above "^M" is added by me, as carriage return would not be visible in browser.

If you're interested, I can send you the excel file with the offending content.

I need your help on how to avoid those offending string, or the carriage returns. (I even try to do string Replace of the carriage return or new line, as I found that once I manually deleted whatever caused change to another line, the problem would be gone. But calling Replace to replace vbNewline, Chr$(13), or vbCrLf did not make any difference.

Thanks for your further help!

Yu

1
  • 1
    What is different on the Print line in program that doesn't print ^M?
    – poke
    Feb 25, 2012 at 14:37

2 Answers 2

24

Use a trailing semicolon to surpress the new line:

Print #outFile, "#+TITLE:     Weekly Report";
                                            ^
                                            ^

The VB Editor will often add a semicolon if you make a mistake in the statement which could explain why the new line is sometimes output and sometimes not.

New diagnostic routine

We need to know the character within cell A1 that is causing the problem.

Place the following subroutine within one of your modules.

Public Sub DsplInHex(Stg As String)

  Dim Pos As Long

  For Pos = 1 To Len(Stg)
    Debug.Print Hex(AscW(Mid(Stg, Pos, 1))) & " ";
  Next
  Debug.Print

End Sub

Go to VB Editor's Immediate window and type in the following text following by Return:

DsplInHex(Sheets("Sheet1").range("A1"))

Underneath this line, you should see something like 54 65 73 74 31. This is a list of the code value of each character in the cell. I expect we will see A, the code for line feed, or D, the code for carriage return, at the end of the list.

Position the cursor in cell A1. Click F2 to select edit then Backspace to delete the invisible trailing character then Return to end the edit. Go back to the Immediate Window, position the cursor to the end of DsplInHex(Sheets("Sheet1").range("A1")) and click Return. The trailing character should have gone.

Try that and report back. Good luck.

5
  • 1
    Thanks! Your idea works. Actually, with semicolon. there will not be any end of line at all. Consecutive print statements would be on the same line. So at the end of a line printout, it should be like the following: Print #outFile, "#+TITLE: Weekly Report" & vbNewLine; to achieve the desired result of having newline at the end.
    – Yu Shen
    Feb 26, 2012 at 10:17
  • Sorry I did not make the purpose of the semicolon as clear as I should have. If you read the documentation on the Print # Statement you will find semicolon mentioned under charpos. "XX" & vbNewLine; is exactly the same as "XX". vbNewLine adds an extra new line so you can output several lines in a single statement. ; says the next output is to follow immediately. The rules are the same for Debug.Print which writes to to the Immediate Window. I suggest you experiment. Feb 26, 2012 at 10:58
  • Sorry, this solution does not solve my problem. Please see my further characterization of my problem above.
    – Yu Shen
    Mar 3, 2012 at 14:09
  • I have added a new section to my answer which I hope will allow us to identify the problem. Mar 3, 2012 at 14:53
  • 1
    Hi Tony, your suggestion worked! Using your script, I printed out the values of offending string. The hex code is 20 A (that is space followed by newline). With the finding, I used replace function to replace newline by space, then the problem solved! It was a nasty bug of VBA 6 (with Excel 2007).
    – Yu Shen
    Mar 4, 2012 at 12:53
4

To help the other people in the future, here is an summary of my problem and the solution. The extra carriage return on each line even with semi-colon at the print statement end was actually caused by a string of space followed by newline (Chr$(A)) in one of the print statement, once such string is printed, then all previous and subsequent printed content would have an extra carriage return!

It seems a bug on VBA 6 (with Excel 2007), a nasty one!

My work-around was to replace the newline by a space.

Thanks for Tony's repeated help enabling me finally nailed down the cause.

Here is the code to demonstrate the problem:

Sub DemoCarriageReturnWillAppearOnAllLines()
    Dim filePath As String
    Dim outFile
    Dim offendingText
    filePath = "d:\tmp\demoCarriageReturn.org"
    If Dir(filePath) <> "" Then
        Kill filePath
    End If
    outFile = FreeFile()
    Open filePath For Output As outFile
    Print #outFile, "#+AUTHOR:    Yu Shen" & vbNewLine;
    Close #outFile 'At this moment, there is no carriage return
    Open filePath For Append As outFile
    offendingText = " " & Chr$(10)
    Print #outFile, offendingText & vbNewLine;
    Close #outFile 'Now, every line end has carriage return.
    'It must be caused by the offending at the above print out content.
End Sub

After the first "Close #outFile", here is the content of the file demoCarriageReturn.org:

#+AUTHOR:    Yu Shen

Note: with editor capable showing carriage return as visible ^M, there is no carriage return present.

However, after the second "Close #outFile", here is the content of the same file with additional content:

#+AUTHOR:    Yu Shen^M

^M 

Note: there are two carriage returns appear. They are not intended. Especially, to the first line, the print statement has been executed, and at the previous close statement, it was found without carriage return. (To illustrate carriage return, I have to typing ^M in web page here. But it's in the file of the print out.)

This is why I think that it's a bug, as the carriage returns are not intended. It's undesirable surprise.

The following code shows that if I filter out the linefeed character the problem would be gone.

Sub DemoCarriageReturnWillNotAppearAtAll()
    Dim filePath As String
    Dim outFile
    Dim offendingText
    filePath = "d:\tmp\demoCarriageReturn.org"
    If Dir(filePath) <> "" Then
        Kill filePath
    End If
    outFile = FreeFile()
    Open filePath For Output As outFile
    Print #outFile, "#+AUTHOR:    Yu Shen" & vbNewLine;
    Close #outFile 'At this moment, there is no carriage return
    Open filePath For Append As outFile
    offendingText = " " & Chr$(10)
    Print #outFile, Replace(offendingText, Chr$(10), "") & vbNewLine;
    Close #outFile 'Now, no more carriage return.
    'The only change is removing the linefeed character in the second print statement
End Sub

After full execution of the above program, there is indeed no carriage return!

#+AUTHOR:    Yu Shen

This shows that string combination of space followed by linefeed caused the bug, and removing linefeed can avoid the bug.

The following code further demonstrate that if there is no offending string, even without newline and semi-colon at the end of print statement, there would not be undesired carriage return!

Sub DemoCarriageReturnWillNotAppearAtAllEvenWithoutNewLineFollowedBySemiColon()
    Dim filePath As String
    Dim outFile
    Dim offendingText
    filePath = "d:\tmp\demoCarriageReturn.org"
    If Dir(filePath) <> "" Then
        Kill filePath
    End If
    outFile = FreeFile()
    Open filePath For Output As outFile
    Print #outFile, "#+AUTHOR:    Yu Shen"
    Close #outFile 'At this moment, there is no carriage return
    Open filePath For Append As outFile
    offendingText = " " & Chr$(10)
    Print #outFile, Replace(offendingText, Chr$(10), "")
    Close #outFile 'Now, no more carriage return.
    'The real change is removing the linefeed character in the second print statement
End Sub

Also in the output result:

#+AUTHOR:    Yu Shen

Still no the annoying carriage return!

This shows that using newline followed by semi-colon at the end of print statement is not the solution to the problem of carriage return at every line! The real solution is to avoid any string of space followed by linefeed in the print out content.

Yu

6
  • I am glad we found the source of your problem but this is not a bug. You can enter a linefeed into a cell with Alt+Return. People use it break long text fields into paragraphs. You did not to use Replace. If you had editted the cell, you would have seen that the cursor was underneath the text. Backspace would have removed the linefeed and caused the cursor to move up to the end of the previous line. Mar 4, 2012 at 16:36
  • But I'm amazed that with just one string of space followed by linefeed, VBA adds carriage return to all print out lines even before the offending string was printed! This is not really a desirable behavior. It would be OK to preserve the linefeed for the print out string with the linefeed.
    – Yu Shen
    Mar 4, 2012 at 23:03
  • 1
    The specification for the Print # statement is absolutely clear: "If charpos is omitted, the next character is printed on the next line." That is, a line feed will be added to the output string unless you state explicit that it is not to be added. Print #fn "Line 1" & vbLf & "Line 2" & vbLf & "Line 3" is valid. That is, one Print # statement can result in many lines of output. The compiler cannot know that you did not mean to have a linefeed at the end of the cell value; it does what it is told to do not what you meant to tell it to do. Mar 4, 2012 at 23:54
  • Being able to include line feeds in strings is sometimes convenient. It was not convenient for you on this occasion but that does not make it a bug. Now that you know that you can include line feeds in print strings, it will not be long before you take advantage of this facility. Mar 4, 2012 at 23:55
  • Sorry, Tony, I just wanted to indicate that the real solution is to avoid the string of space followed by linefeed in the print out content. You did help me to find the solution. But using newline followed by semi-colon at the end of print statement is actually not the solution. Without the offending string, without newline and semi-colon would be still OK, no carriage return would be introduced. With offending string, your suggestion, still did not help. Thank you very much for your help. You helped me to debug this problem.
    – Yu Shen
    Mar 6, 2012 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.