在使用Visual Basic时,我对Print语句的行为感到困惑,有时候以下语句:会导致在行末添加额外的回车符"^M",但有时候却不会。我想知道这是为什么?
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"
会产生
#+TITLE: Weekly Report^M
当我希望没有 ^M 的时候:
#+TITLE: Weekly Report
在一个测试程序中,几乎相同的代码不会产生"^M"。
请帮忙!非常感谢。
经过进一步实验,我发现以下建议使用vbNewline和";"在打印内容末尾,仍然不能解决我的问题。
经过仔细分离,我发现问题的原因是一个看起来像空格但并不完全相同的字符,跟随换行和回车。在打印包含有冒犯字符串的文本之前,没有回车符,但是一旦该行被打印,那么每一行(包括之前打印的行)都将有回车符。
由于我对VBA的技能还不太好,我不确定确切的冒犯字符串是什么。
这里是从电子表格单元格复制的冒犯文本:
"There is something invisible after this visible text
After the invisible text, then there might be a carriage return $Chr(13) and/or newline"
我不确定将内容粘贴到Web浏览器是否会保留该内容。通过将其粘贴到Emacs中,我没有看到回车符号,而如果存在回车符号,Emacs应该会显示它。因此,我猜测该字符串中没有回车符号。
以下是演示问题的程序:
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
以下是上述过程的最终结果:
#+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
请注意,上面的 "^M" 是由我添加的,因为在浏览器中回车符不可见。
如果您感兴趣,我可以发送带有有问题内容的 Excel 文件。
我需要您的帮助,以避免那些有问题的字符串或回车符。(我甚至尝试使用字符串替换回车符或换行符,因为我发现一旦手动删除造成另一行改变的内容,问题就会消失。但是调用 Replace 来替换 vbNewline、Chr$(13) 或 vbCrLf 没有任何效果。
感谢您的进一步帮助!
Yu