Printing Excel File Name to Text File - Why am I getting false? - excel

Here is the small script I wrote:
Option Explicit
Dim strFileFullName As String
Sub saveToText()
Open "PATH\File.txt" For Append As #1
Print #1, strFileFullName = ActiveWorkbook.FullName
Print #1, Sheets("Overview").Range("D14").Text
Close #1
End Sub
Also I would like to add some extra text to the .txt file that is not in the excel workbook. How would I go about doing that? Thanks!

VB does not have a distinction between the comparison operator and the assignment operator. That is, they are both =. In this case, it is being interpreted as the comparison operator, which is returning false. (Compare this to C, where the comparison operator is == and the assignment operator is =; what you are trying to do here would work in C as an inline assign)
It doesn't look like you need the extra variable there, so you should be able to just do:
Print #1, ActiveWorkbook.FullName
Or, use two statements (VB will understand this as an assignment, not a comparison):
strFileFullName = ActiveWorkbook.FullName
Print #1, strFileFullName
Adding text is as simple as adding another print statement:
Print #1, "Lorem ipsum dolor"

Related

How to avoid carriage return when using #print with excel vba [duplicate]

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

printing txt file from VBA for Matlab

I am working parallel with Excel and VBA in order to create txt files I wish to use for MATLAB. However, I experience some format issues I can't resolve.
For instance, the following VBA
Open "example.txt" For Output As #1
For i = 1 To 5
Print #1, Sheets("Example").Cells(i + 3, 3)
Next i
Indeed prints numbers (reals) it is supposed to however MATLAB struggles with reading this example .txt file.
There are some characters VBA is printing. I don't know how to delete those within a VBA code.
Example.txt opened in matlab. Note the NaN read by MATLAB from a text file:
VBA text file - Note a line as the first element of a column
Perhaps there is a character that is invisible.
A possible solution is to remove those characters with regex.
Add reference to Microsoft VBScript Regular Expression 5.5
Then the following VBA code:
Set re = New RegExp
re.Pattern = "[^0-9]"
Open "example.txt" For Output As #1
For i = 1 To 5
Print #1, re.Replace(Sheets("Example").Cells(i + 3, 3).value, vbNullString)
Next i
This should remove anything that is not a digit from the cell before printing it to the text document.

Multiple space delimiter split string

I have a string like
string = "computer prog <5spaces> data mining <5spaces> oops concept"
As we can see clearly computer prog, data mining etc., are one continuous string and the delimiter is 5 spaces between the strings " ".
I need to split based on this in vb.net - so far I tried regex.split which works but results in giving 2 empty strings additionally and it's tedious to remove those additional strings.
I also tried using the string.split method but again it's taking even single white space also delimiters.
Below are the tried options:
regex.split
string.split
None give me the required result. I am not sure what I need to use. I even tried the option of stringsplitoption.removesapceentry (something like that) to get the desired result inside the split method, but none worked.
Dim array_keyskills As String() = res.Split(" ".ToCharArray,StringSplitOptions.RemoveEmptyEntries)
system.Windows.MessageBox.Show(array_keyskills(2) & array_keyskills.Length & " key skills") 'Display
The following short program:
Module Module1
Sub Main()
Dim s = "computer prog data mining oops concept"
Dim parts = s.Split({" "}, StringSplitOptions.None)
For Each p In parts
Console.WriteLine(p)
Next
Console.ReadLine()
End Sub
End Module
outputs:
computer prog
data mining
oops concept
If your data does not work that way then you should examine it to find which whitespace characters are in it which appear to be spaces but are not.
This did the trick:
array_keyskills = System.Text.RegularExpressions.Regex.Split(res," ").Where(
Function(s) Not String.IsNullOrWhitespace(s)
).ToArray()

Removing unwanted data from text file

I have a large text file exported from an application that has three unwanted zeros in each row. The text file needs to be imported into another application and the zeros cause a problem.
Basically the unwanted three zeros per row need to be deleted. These zeros are always in the same location (same number of characters when counting from the left), but the location is somewhere in the middle. I have tried various things like importing the file into excel, removing the zeroes and then exporting as text file, but always have formatting problems with the exported text file.
Can someone suggest a solution or point me in the right direction?
something like this ? (quickly done)
Sub replaceInTx()
Dim inFile As String, outFile As String
Dim curLine As String
inFile = "x:\Documents\test.txt"
outFile = inFile & ".new.txt"
Open inFile For Input As #1
Open outFile For Output As #2
Do Until EOF(1)
Line Input #1, curLine
Print #2, Replace(curLine, "000", "", 6, 1, vbTextCompare)
Loop
Close #1
Close #2
End Sub
Alternatively, you can do that with any text editor that allows block selection (I like Notepad2, tiny, fast and portable)
I see you use excel a lot.
When you import the text file into excel do you use the import function and do you push the data into separate cells?
if the cell is numeric you could do the following:
=LEFT(TEXT(G5,"#"),LEN(TEXT(G5,"#"))-3)
if the cell is text:
=LEFT(G5,LEN(G5)-3)
G5 would the cell the data row/field is in.
curLine = Left(curLine, 104)
This will take the first 104 characters

Remove newline while writing to text

This simple macro will write the text "ABC" to the file temp.txt under E: drive. However if we open the text file, notice that there is a new line char after C. How can we get rid of this, so that it will end after C
Code:
Sub ExamplePrint
i = FreeFile()
Open "e:\Temp.txt" For Output As i
Print #i, "ABC"
Close #i
end Sub
In vba if we give like this, the newline doesnt come. however in openoffice the whole text document comes as empty
Code:
Print #i, "ABC";
Try the FileSystemObject:
http://msdn.microsoft.com/en-us/library/6ee7s9w2%28v=vs.85%29.aspx

Resources