Change value of the column .csv file using Access VBA - vba

I have a .dat file that I saved as a .csv and it imports in a table, OK. But this file has in the first column = HOUR "hnnss". The file name contains the date that I already managed to separate it and save it in a variable=date.
My problem is: when saving the file as .csv I need to open the file, change the values of the first column from hnnss to data hh:nn:ss and then save and close, only then do I import it into the table. It needs to be in that sequence. Thanks for help.
PS: I'm using Access 365 + VBA 7.1

Andreia: You can read the file using method like in here Import csv to array and in this loop :
For i = 2 To UBound(aryFile) - 1 ' in your case start with second line
tsOut.WriteLine aryFile(i)
Next
implement the formatting like this:
' in your case start with second line if the 1st is header
For i = 1 To UBound(aryFile) - 1
aryRow = Split(aryFile(i), ",")
aryRow(0) = formatTime(aryRow(0), aryRow(?)) ' replace ? with index of date field
tsOut.WriteLine Join(aryRow,",")
Next
The above code is using function formatTime(fieldWithTime, fieldWithDate) which you need to write and which returns your formatted string for the whole date. I leave it for you. If you won't be able to code it let me know but in that case you rather read some books about VBA programming.
Note: I did not debug the code. This is just an idea.

Related

External file properties not updated - VBA

I have a macro that reads out external file properties like date created. The file from where I read is stored on a server. Unfortunately the date returned is not the correct one when running the macro the first time. Only when I open the file or when I run the macro several times, the correct updated date created is returned.
Does anyone have an idea how to solve that issue except from opening the file or looping through until the date is correct?
Here is the code:
strFilename = "<FILENAME>"
Workbooks.Open strFilename
Workbooks("strFilename").Close
Set oFS = CreateObject("Scripting.FileSystemObject")
lastcreatedLTVfile = CDate(Format(oFS.GetFile(strFilename).DateCreated, "dd.mm.yyyy"))
Do you want DateCreated or do you actually want DateLastModified? In your question you say "correct updated date" so I guess you should be using DateLastModified.

VBA Reading From a UCS-2 Little Endian Encoded Text File

I have a whole bunch of text files that are exported from Photoshop that I need to import into an Excel document. I wrote a macro to get the job done and it seemed to work just fine for my test document but when I tried loading in some of the actual files produced by Photoshop Excel started putting all the data in a separate column except for the first line.
My code that reads the text file:
Open currentDocPath For Input As stream
Do Until EOF(stream)
Input #stream, currentLine
columnContents = Split(currentLine, vbTab)
For n = 0 To UBound(columnContents)
ActiveSheet.Cells(row, Chr(64 + colum + n)).Value = columnContents(n)
Next n
row = row + 1
Loop
Close stream
The text files I am reading look like this, only with much more data:
"Name" "Data" "Info" "blah"
"Name1" "Data1" "Info1" "blah1"
"Name2" "Data2" "Info2" "blah2"
The problem seemed pretty trivial, but when I load it into excel, instaed of looking like it does above it looks like this:
ÿþ"Name" "Data" "Info" "blah"
Name1
Data1
Info1
blah1
Name2
Data2
Info2
blah2
Now I am not sure why this is happening. It seems like the first two characters in the first row are there because those bytes declare the text encoding. Somehow those characters keep the first row formatted correctly while the remaining rows lose their quotation marks and all get moved to new lines.
Could someone who understands UCS-2 Little Endian text encoding explain how I can work around this? When I convert the files to ASCII it works fine.
Cheers!
edit: Okay so I understand now that the encoding is UTF-16 (I don't know a whole lot about character encoding). My main issue is that it's formatting strangely and I don't understand why or how to fix it. Thanks!
As I mentioned in my comment, it appears the file you're trying to import is encoded in UTF-16.
In this vbaexpress.com article, someone suggested that the following should work:
Dim GetOpenFile As String
Dim MyData As String
Dim r As Long
GetOpenFile = Application.GetOpenFilename
r = 1
Open GetOpenFile For Input As #1
Do While Not EOF(1)
Line Input #1, MyData
Cells(r, 1).Value = MyData
r = r + 1
Loop
Close #1
Obviously I can't test it myself, but maybe it'll help you.
Why not just tell excel to import the file. MS has probably put hundreds of thousands of person hours into that code. Record the importation to get easy code.
Remember Excel is a tool for non programmers to do programming things. Use it instead of trying to replace it.
These are the replacement file functions that you use for new code. Add a reference to Microsoft Scripting Runtime.
Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
object.OpenTextFile(filename[, iomode[, create[, format]]])
Arguments
object
Required. Object is always the name of a FileSystemObject.
filename
Required. String expression that identifies the file to open.
iomode
Optional. Can be one of three constants: ForReading, ForWriting, or ForAppending.
create
Optional. Boolean value that indicates whether a new file can be created if the specified filename doesn't exist. The value is True if a new file is created, False if it isn't created. If omitted, a new file isn't created.
format
Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.
The format argument can have any of the following settings:
Constant Value Description
TristateUseDefault
-2
Opens the file using the system default.
TristateTrue
-1
Opens the file as Unicode.
TristateFalse
0
Opens the file as ASCII.

How to search data in a txt file through Visual Basic

I have this txt file with the following information:
National_Insurence_Number;Name;Surname;Hours_Worked;Price_Per_Hour so:
eg.: aa-12-34-56-a;Peter;Smith;36;12
This data has been inputed to the txt file through a VB form which works totally fine, the problem comes when, on another form. This is what I expect it to do:
The user will input into a text box the employees NI Number.
The program will then search through the file that NI Number and, if found;
It will fill in the appropriate text boxes with its data.
(Then the program calculates tax and national insurance which i got working fine)
So basically the problem comes telling the program to search that NI number and introduce each ";" delimited field into its corresponding text box.
Thanks for all.
You just need to parse the file like a csv, you can use Microsoft.VisualBasic.FileIO.TextFieldParser to do this or you can use CSVHelper - https://github.com/JoshClose/CsvHelper
I've used csv helper in the past and it works great, it allows you to create a class with the structure of the records in your data file then imports the data into a list of these for searching.
You can look here for more info on TextFieldParser if you want to go that way -
Parse Delimited CSV in .NET
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(FileName)
Dim CurrentRecord As String() ' this array will hold each line of data
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {";"}
afile.HasFieldsEnclosedInQuotes = True
' parse the actual file
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
I'd recommend using CsvHelper though, the documentation is pretty good and working with objects is much easier opposed to the raw string data.
Once you have found the record you can then manually set the text of each text box on your form or use a bindingsource.

How to import part of a file name to a field

I have a file that i import into access 2007 and i was wondering if i can take part of that file name and put it into a field in access? For example here is one example of a file name:
"20140211_agent_statistics.csv"
I have done some research on this but cant seem to find the answer when numbers change all of the time. I just need to grab the numbers on this file name. However, these numbers change all of the time. Does anyone have a solution for this? Thank you in advance. Any help and code is much appreciated i am very new to vba.
Working on a few assumptions:
You are importing this by code so it picks up the file name?
The numbers are the date so probably always 8 characters long?
If you import by code you will assign the file name to a variable, in case you don't here is how to:
Dim strFileO as String, strFileLoc as String
strFileLoc = "C:\YourFolder\" ' Folder where file is saved
strFileO = Dir(strFileLoc & "*.csv")
Above will pick up any .csv file in the folder, you should move them once imported
Once you have the strFileo then to get the date:
Dim lDate as Long
lDate = Left(strFileO,8)
'Or if the numbers aren't always 8 characters:
lDate = Left(strFileO. InStr(strFileO,"_") - 1) ' Assumes numbers followed by "_"

Modify Excel File and save as CSV using vba

I am working on populating a new application full of resident data. I have to export a list of residents for each property. Unfortunatly the new application has to have the residents imported 1 property at a time. This means im stuck loading 200+ properties by exporting an excel file, slightly modifing the data and then importing into the new application.
For each property that is exported I must remove a '-' from the first column and i have to remove all of the ',' throughout the entire document. I then change the formating on a date column to 'mm/dd/yyyy'. Then the document is saved as a CSV and can be imported.
I would like to write a script that can perform the updates to the excel file and save it to a csv. Please advise if this is worth my time. This is a one time load so it might be better to just power through.
Thank You
Possibly a little prematurely, as I'm not certain this is what you want to achieve, but you could try this (save first):
Sub replaceStuff()
ActiveSheet.Range("A:A").Replace "-", ""
ActiveSheet.Cells.Replace ",", ""
ThisWorkbook.SaveAs "doc", xlCSVWindows
End Sub