Add 'sep=' line to the csv file - excel

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.

Related

Rename txt files with ADODB without creating a new one

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

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.

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()

Editing a Hex Stream in VBA Before Saving to File

Background: I am extracting a file that is saved in a SQL database using an ADODB connection. One column of the database is the filename, including the file extension, and another is the actual contents of the file as a hex stream. I would like to save this file and open it.
Problem: This works fine with .pdf files. However, with .png files there is an error- the file is corrupted when I try to open it. I used a hex editor (HxD) and noticed that there were excess values. If I remove these the file opens fine. The hex stream should begin with the "per mille" character (Chr(137) in excel) in order for the file to open. I have not found a way to edit the hex stream in excel without converting it to characters.
The .png file opens with no problem when I take out the first few characters using a hex editor so that the file begins with:
‰PNG
Or the equivalent in hex code:
89 50 4E 47
The excess characters are
ÿþ
Or the equivalent in hex code:
FF FE
(I am trying to remove these). These characters are in the saved file even when I remove 4 characters from the text string using
Content = Right(Content, Len(Content) - 4)
It's almost like they automatically get added before the string when I save the file.
Code:
Calling the save to file function, where Content is the file content and Name is the filename:
Call StringToTextFile("C:\", rst![Content], rst![Name])
The function is below:
Public Sub StringToTextFile(ByVal directory As String, ByVal Content As String, ByVal filename As String)
'Requires reference to scrrun.dll
Dim fso As Scripting.FileSystemObject
Dim ts As Scripting.TextStream
Set fso = New Scripting.FileSystemObject
If Right(filename, 4) = ".png" Then 'recognizing the .png file
'Content = CByte(Chr(137)) & Right(Content, Len(Content)) 'unsuccessful attempt at inserting "per mille" character
'iret = InStr(0, Chr(137), Content, vbBinaryCompare) 'unsuccessful attempt at finding the "per mille" character in the content
End If
Set ts = fso.CreateTextFile(directory & filename, True, True)
ts.Write Content
ts.Close
Dim myShell As Object
Set myShell = CreateObject("WScript.Shell")
myShell.Run directory & filename 'Open the saved file
End Sub
When I try to insert the "per mille" character using Chr(137) it just shows a blank space in the hex editor.
Any help is appreciated!
This seems to be a similar discussion, but I am unsure how to apply this to my case:
excel-vba-hex-to-ascii-error

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