How can I write to a text file using VBA? - excel

I am programming in VBA and I have a string variable which contains my data. I would like to write these data to a .txt file and leave this txt file open once the script has ended running.
How can I program that?
Thanks in advance!

Something like:
Sub GergoBarta()
Close #1
Open "C:\TestFolder\TestFile.txt" For Output As #1
MyText = "Hello World"
Print #1, MyText
End Sub

Related

VBA Excel, when I read from a text file into a (string) variable, why does it not read Carriage return and line feed characters (0d 0a)

I am working on a macro that takes data from a textbox and writes it to a file. The data includes carriage return/Linefeed characters. At a later stage, I need to read the data from the file and put it back in the textbox in exactly the same form. When I do this, the Cr/Lf characters (0d 0a) are missing. I have established that they are written to the file but not read back. I am using the following snippet to write the file:
Print #1, Temstg
Close #1
and reading it using the following snippet:
Do Until EOF(1)
Line Input #1, T
Temstg = Temstg & T
Loop
Close #1
Where am I going wrong
Rob
As said in the comment Line Input considers newline character as the separator for a new line. Here is the documentation.
The following code reads the complete text file in one shot including newline characters.
Sub ReadFIle()
Dim fileName As String: fileName = "C:\temp\yourfile.txt"
Dim fileContent As String
Dim File As Integer: File = FreeFile
Open fileName For Input As #File
fileContent = Input(LOF(File), File)
Close #File
' example how to split the file in lines then
Dim vDat As Variant
vDat = Split(fileContent, vbNewLine)
End Sub
Reading on Input function

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

VB: Highlight Excel cell in worksheet

I was wondering if it was possible to create a vbs file to highlight a cell in an excel workbook.
I have an excel worksheet with multiple computer host-names, I also run a script in batch that pings each host-name in a text document. I want to call the vbs file to highlight the cell in excel if the ping result was successful. Is this possible?
Thanks!
Dimitri
There are plenty of ways to do this, but I must ask why you're using a batch script and a text file to ping the hostnames when you can do that right in Excel?
There are two ways to do this... one is a bit more complex and correct and the other is quick and dirty. Frankly, I recommend the quick and dirty.
Correct Way:
Declare the ReadConsole & WriteConsole methods from your Windows kernel32.dll and utilize them to get the results of your ping. It's described well here:
http://visualbasic.about.com/od/learnvb6/l/bldykvb6dosa.htm
Q&D Way:
Use the built-in Shell() function in VBA and pipe the output of the ping to a text file. Parse said text file and delete it when you're done.
e.g.
for each currCell in hostnameRange
' Ping each hostname and pipe the results to a file
shell "ping " + currCell.value + " >> ping_result.txt"
next currCell
inFile = FreeFile()
Open "ping_result.txt" for Input as #inFile
fileBuffer = Input$(LOF(inFile ), inFile) ' Open and read the file to a buffer
for each currCell in hostnameRange
' Search for ping failures in the buffer
if instr(1, fileBuffer, "could not find host " + currCell.value) = 0 then
debug.print "Ping successful."
end if
next currCell

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

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"

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