error writing in file vba - excel

I'm trying to write a file using VBA. My code is below. It worked the first time, but when i closed the excel file (.xlsm) and try to use it again, it doesn't work.
I do not get any errors when running the macro but the new file does not appear
Sub LogInformation(LogMessage As String)
Const LogFileName As String = "TEXTFILE.db"
Dim FileNum As Integer
FileNum = FreeFile ' next file number
Open LogFileName For Append As #FileNum ' creates the file if it doesn't exist
Print #FileNum, LogMessage ' write information at the end of the text file
Close #FileNum ' close the file
End Sub

Sorry guys. That was dumb.
The default relative path is in User/%MyUser%/Documents.
I need to use ChDir then open/write/close the file.
Chdir(ActiveWorkbook.Path)

Related

VBA: File name and path as variables

I'm super green/new to VBA.
I've got a file location that I enter in on Sheet 4. That reads in fine.
Then I've got a file name using the DIR function, again that's fine.
Now I want to Open my file, however I can't get it to work this way. I can't hard code the file name (it's too long).
There's got to be a simple way to do this. I've seen some examples but they look way too complicated, it's got to be like 2 lines max from what I've got.
Any thoughts?
Sub data_import_new()
'
' data_import_new Macro
Dim File_Location As String
Dim File_Name As String
Dim text As String
File_Location = Sheet4.Cells(3, 5).Value
File_Name = Dir(Residual_File_Location & "\*.txt")
Open Residual_File_Name For Input As #1
Input #1, text
MsgBox text
Close #1
End Sub

Excel VBA not writing to next text file line

I have the following macro that is should write new data onto a new line in a text/csv file, however it overwriting the existing text in the file, I thought that write wrote to a new line as opposed to print. I am not sure what I am doing wrong
Sub picking()
Range("d14").NumberFormat = "mm/dd/yyyy"
Range("d14").Value = Now
Range("e14").NumberFormat = "hh:mm"
Range("e14").Value = Now
Range("e17").Value = "Picking"
Call outputcsv
End Sub
Sub outputcsv()
Dim Fullpath As String
Dim outputstring As String
Fullpath = Worksheets("Maintence").Range("c5")
Open Fullpath For Output As #1
outputstring = Worksheets("CSV").Range("A1")
Write #1, outputstring
Close #1
End Sub
You just need to change...
Open Fullpath For Output As #1
...to...
Open Fullpath For Append As #1
Note that "Output" changes to "Append."
Also note that "Append" will create the file - just as Output does - if it doesn't already exist. No need to pre-create it.

"File already open" when trying to open a text file

What I want to do: I have an Log.txt where special values from an Excel-Sheet are listed. Anytime the Macro is executed, it checks for new special values. Before adding them to the Log.txt via a Sub, the same Sub checks if the corresponding value (they are unambigous) is already on the Log-List. If this is not the case, the value should be added to the list.
My approach: You can see my current approach in the code example below.
Dim FileNum as Integer
dim DataLine as String
Dim strPath as String
Dim strEntry as String
strPath = [Path to Log.txt]
strEntry = [Special Value]
'In this first part the Log.txt is opened for Input and each line is saved in DataLine
'to be compared to the special value in strEntry. If it is already in the Log.txt, the Sub to
'create a new Log-Entry is exited and is started again, once the next special value from another cell is
'obtained (from another Sub).
FileNum = FreeFile()
Open strPath For Input As #FileNum
Do While Not EOF(FileNum)
Line Input #FileNum, DataLine
'The value strEntry should start at position 2 of the Entry in the Log.txt (due to the quotation marks [""] in the
'Log.txt line.
If InStr(DataLine, strEntry) = 2 Then Exit Sub
Loop
Close #FileNum
'After it could be verified, that strEntry is not already in the Log.txt, the txt-File should be opened
'again, this time for Append. Then, the strEntry should be written to the txt-File, the Log.txt should close and
'Sub is finished.
FileNum = FreeFile()
Open strPath For Append As #FileNum
Write #FileNum, strEntry
Close #FileNum
The Problem: I observed, that the first part of the Sub is working fine. If strEntry is already in the Log.txt, the Sub is exited and the whole Macro is jumping to the next special value. If this value is not already in the txt-File, the first part of the Sub does not exit the Sub and it jumps to the second part, where it should append the value to the Log.txt.
This is where the problem is. If I exclude the first part of the Sub, I could verify, that the second part is also working fine (as he simply appends all values to the txt-File). But once I have the first part included, I get the Error-Message
File already open.
I can not figure out, why this is happening, as I Close #FileNum at the end of part one.
I thank in advance for your ideas and solutions.
The problem is If InStr(DataLine, strEntry) = 2 Then Exit Sub You are not closing the file in this case as it is exiting the Sub. In this case file remains open. Use Exit Sub judiciously. Try and have one entry point and one exit point so that you can dispose objects/variables and do relevant cleanup correctly.
One way: Using a Boolean Variable
'
'~~> Rest of your code
'
Dim continue As Boolean: continue = True
'
'~~> Rest of your code
'
Do While Not EOF(FileNum)
Line Input #FileNum, DataLine
If InStr(DataLine, strEntry) = 2 Then
continue = False
Exit Do
End If
Loop
Close #FileNum
If continue = True Then
FileNum = FreeFile()
Open strPath For Append As #FileNum
Write #FileNum, strEntry
Close #FileNum
End If
Another way: Using GOTO
FileNum = FreeFile()
Open strPath For Input As #FileNum
Do While Not EOF(FileNum)
Line Input #FileNum, DataLine
'The value strEntry should start at position 2 of the Entry in the Log.txt (due to the quotation marks [""] in the
'Log.txt line.
If InStr(DataLine, strEntry) = 2 Then GoTo CleanupAndExit
Loop
Close #FileNum
'After it could be verified, that strEntry is not already in the Log.txt, the txt-File should be opened
'again, this time for Append. Then, the strEntry should be written to the txt-File, the Log.txt should close and
'Sub is finished.
FileNum = FreeFile()
Open strPath For Append As #FileNum
Write #FileNum, strEntry
CleanupAndExit:
Close #FileNum

VBA: Line Input #, next file not showing new data

I'm reading multiple csv files into excel for some number crunching. The file reads appear to work with each excel column having the csv file name inserted for confirmation. Odd thing. Each csv file name is correctly inserted into the sheet, but the data is all the same as the first file.
Is there a way to flush / reset ..... something, so the next read file data actually is the next file?
Excel VBA code snippet:
Public Const sRawFilePath As String = "\\server1\Sample.RAW.Files\"
----------------
Sub ImportCSV()
Dim sFullFilePath, sFile As String
fFIle = FreeFile()
sFile = Dir(sRawFilePath & "*.csv")
sFullFilePath = sRawFilePath & sFile
While sFile <> ""
Open sFullFilePath For Input As fFIle
While Not EOF(fFIle)
Line Input #fFIle, sLine
""
"take the sLine string and separate the comma delimited values for insertion into columns "
"This part works fine"
""
Wend
Close fFIle
sFile = Dir()
Wend
End Sub
Stepping through the code I can confirm the next file is in the queue, but the read data is not representing the next file, just the first file, ... and always the first file even though 20 more files are read.
PS - This forum has been an amazing resource.
The problem is you define sFullFilePath which locks in the file that you're opening. So even though you're successfully looping through the files with Dir, you will only open the first one because you locked it in. Don't use that variable at all:
'Change this line
Open sFullFilePath For Input As fFIle
'To be this instead
Open sRawFilePath & sFile For Input As fFIle
Rather than executing Dir(sRawFilePath & "*.csv") in every call, you should just execute Dir in subsequent calls. The error causes you to re-read the first file again and again.

Excel Export as Unicode Pipe Delimited

Right now I'm trying to save an excel sheet with VBA as a pipe delimited unicode file with a .txt extension.
I've figured out how to save it as unicode with code as follows
ActiveWorkbook.SaveAs FileName:=FileName, _
FileFormat:=xlUnicodeText
But this will save it as tab delimited. I can't seem to find an option with MSDN, as their page on FileFormat isn't very helpful.
As saving as a .csv doesn't keep it unicode, you can try replacing the tabs by pipes in the text file, using a macro like this one, found here. You can call it using
call TextFileReplace("C:\temp\test.txt","C:\temp\test2.txt",vbtab,"|")
Public Sub TextFileReplace(ByVal sFile As String, ByVal sNewFile As String, ByVal sFind As String, ByVal sReplace As String)
Dim iFile As Integer
Dim sTextBuffer As String
'
' Get the next available file handle
iFile = FreeFile
' Open the source file (sFile) for read access
Open sFile For Binary Access Read As iFile
' Create a buffer that will hold the contents of the file
sTextBuffer = Space(LOF(iFile))
' Read the contents of the file into the buffer
Get #iFile, , sTextBuffer
' Close the file
Close iFile
' Use the "Replace" function to replace all instances of
' (sFind) in the buffer with the value in (sReplace)
sTextBuffer = Replace(sTextBuffer, sFind, sReplace)
' Get the next available file handle
iFile = FreeFile
' Open/Create the new file for write access
Open sNewFile For Binary Access Write As iFile
' Write the modified buffer contents to the file
Put #iFile, , sTextBuffer
' Close the file
Close iFile
End Sub
I should also point out that search-n-replace will not properly fix quoted delimiters.

Resources