Rename txt files with ADODB without creating a new one - excel

my problem: I have many text files that I want to rename.
I have been using the ADODB.Stream object to open/read/write the files because they are encoded in UTF-8. So now, if possible, I want to rename the files without the workaround of copying their content, writing their content into a new file with the desired name and deleting the old one. The time stamp on the documents is a valuable information for me, which is why I do not want to create new files.
here is my current workaround that creates new files and deletes the old ones.
Issues with the code:
1) Copied files have new time stamps
2) New Lines don't get copied into the new lines. As they contain some kind of XML code, the generated files become hard to read. I would need to write a piece of code that sets new lines on all appropiate positions after copying.
Sub renameModules()
Dim currentTXT As Variant, newTxt As Variant
Dim currentPath As String, newPath As String
Dim currentContent As String
currentPath = "C:\Users\Me\Desktop\Test\MyCurrent.txt"
newPath = "C:\Users\Me\Desktop\Test\Target001.txt"
Set currentTXT = CreateObject("ADODB.Stream")
currentTXT.Charset = "utf-8"
currentTXT.Open
currentTXT.LoadFromFile (currentPath)
currentContent = currentTXT.ReadText()
Set newTxt = CreateObject("ADODB.Stream")
newTxt.Charset = "utf-8"
newTxt.Open
newTxt.WriteText currentContent
newTxt.savetofile newPath, 1
Kill currentPath
End Sub
For simplicity I have only included the essential steps and omitted all error handling.
My goal: Finding some method to simply rename the current file without fiddling with its content.

No need to deal with ADODB.Stream: You can use the VBA command name not only to rename a file but also to move it to a different folder:
Name currentPath As newPath

Related

Add 'sep=' line to the csv file

The problem is, I want to copy data from .csv file, but excel automatically separates it into columns by comma, I need to separate it by ";".Can I edit csv file using vba code to add 'sep=' at the beginning?
Excel/VBA ignores the separator option if the file has the .csv extension. You have to rename it to set the delimiter. Check out my VBA CSV parser project.
The solution worked for me is to use filesystem object to read csv file and copy it into temporary file with 'sep=' at the first line.
Here is the code:
Function readCsvF(delim as String, fPath as String) As String
Dim sourceFile As Object, objFSO as Object, newTempFile as Object, _
line as String, newName as String
Set objFSO = CreateObject("scripting.FileSystemObject")
Set sourceFile = objFSO.OpenTextFile(fPath)
newName = objFSO.GetParentFolderName(fPath) & "\tempCSVfile.csv"
Set newTempFile = objFSO.CreateTextFile(newName, True)
newTempFile.Writeline("sep=" & delim)
While Not sourceFile.AtEndOfStream
line = sourceFile.Readline
newTempFile.Writeline (line)
Wend
sourceFile.Close
newTempFile.Close
readCsvF = newName
End Function
So what this function does is basically creates new file in which writes first line sep=*'your specified delimiter'* and then copies data from original csv file line by line. This function takes two string parameters: delim is delimiter you want to use and fPath is a path to the csv file, - and returns a path to the new file, so you can open it as workbook and do whatever manipulation you want with it.
Hopefully this will help someone, I really struggled to find the solution, maybe there was any better way, idk.

Open a workbook without knowing the exact name

so i searched but didnt find something good for my use , i have a folder where i will import an excel file , this excel file will have a different name everytime how i can open it with vba , thank you
You can get the file name using the Dir function and multiple character (*) wildcard.
Const Path As String = "C:\Test"
Dim filename As String
filename = Dir(Path & "\*.xlsx")
If Len(filename) > 0 Then
' Do your work
' Remember 'filename' only holds the file name
' you will need to attach the rest of the path to get the full directory.
End If
Note: If there's only one file in the folder you will not have any issues, however if the folder contains multiple files (matching the above pattern), you will need to either loop or provide additional file name characters to the function.
An example:
File name: daily_report_20190404.xlsx
filename = Dir(Path & "\daily_report_*.xlsx")
Hope this helps.

Excel 2010 Macro - Creating txt files with names from ColA and content ColB. Stacko. solutions not work

I have found some answers/examples here on stackoverflow for an issue where in Microsoft Excell 2010, I want to create a txt files for each cell from for e.g. ColumnA which would contain file names, and ColumnB which would contain what is inside certain text file, however one example doesn't work at all, and second bugs after few files created.
You can use the CreateTextFile method which will create your file and provide a TextStream object which you can use to write to the text files. Microsoft Docs
Here's a code example that will do what you asked.
Sub CreateTxt()
Dim my_range As Range
Dim pth As String
Set my_range = Selection
For Each x In my_range.Rows:
pth = "C:\excel_test\" + x.Cells(1) + ".txt" 'file name in column A
Set file_sys = CreateObject("Scripting.FileSystemObject")
Set txt_file = file_sys.CreateTextFile(pth, True)
txt_file.WriteLine (x.Cells(2)) 'content in Column B
txt_file.Close
Next x
End Sub
Just remember, in order to create a file you need adequate permissions on the path you're writing to - I had to run excel as administrator to get the functionality.
Also, the True value in the CreateTextFile method is necessary to overwrite any files with the existing file name, if set to false it will throw an error when trying to write to the file.

How to know numerically the last saved file name

I am creating and saving .ini files in Excel. The files need to follow a specific naming convention that increments by 1 each time a file is created. Not all the files will be created in Excel, some will be done in a separate program. Is there a way to read the saved files in their folder to know which number is next?
For example there are files named exampleFile1.ini through exampleFile63.ini. From Excel using VBA or other means can I see that exampleFile63.ini was the last file and name the next exampleFile64.ini?
Thank you. I'm very new if thats not obvious.
This function will return the next available .INI file name:
Private Function GetNextFile() As String
Dim i As Long
Dim fileName As String
For i = 1 To 1000
' Update Path and File Name prefix below to where your .INI files will be stored.
fileName = "d:\path\exampleFile" & i & ".ini"
If Dir(fileName) = "" Then
GetNextFile = fileName
Exit Function
End If
Next
End Function
Call it like this:
Dim NextIniFile As String
NextIniFile = GetNextFile()

Retrieving last line of a txt file with a VBscript

Before all, I want to say that I am not a programmer, so this may be basic for some people but surely not for me!!
The task that I want to accomplish is to retrieve some characters of a data file that is imported automatically from a server.
Data is stored in lines in a CSV or tabbed .txt file, each line consists of date and some numeric values. The format is always the same, only the file grows in one line each time a new value is entered.
What I need the script to do, is open that file (wich adress is known and constant) search for the last line, and then extract a string from that line and write it on a different .TXT file, from where I can import it to another specific software as a raw value.
The part in the middle (extracting string) is fairly simple, but opening and isolating the last line is far too much for me.
Thanks everybody for helping!
dim path
path = "fileName.txt"
otherOption(path)
function otherOption(fileName)
const read = 1
dim arrFileLines()
set objArgs = CreateObject("scripting.FileSystemObject")
if objArgs.FileExists(fileName) then
set objFile = objArgs.OpenTextFile(fileName,read)
i=0
do until objFile.AtEndOfStream
redim preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
loop
objFile.Close
end if
wscript.Echo arrFileLines(i-1)
end function

Resources