How to import part of a file name to a field - vba

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 "_"

Related

Change value of the column .csv file using Access 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.

System.ArgumentException: 'Illegal characters in path.' Error

Please help. I have a piece of code that's already working in other parks of my program, however fails to work when accessed by a certain form so i can't see there can be an error with it. Its an information storage project using text files. A screenshot of the exact code and the error:
I expected it to change the label text to the contents of the text file its trying to read.
Thanks everyone :)
Well, there must be one or more illegal characters coming from your "zoots1.txt" file!
Build the filename and see what it looks like:
Dim zoot1s As String
zoot1s = My.Computer.FileSystem.ReadAllText("zoot1s.txt")
Dim fileName As String
fileName = zoot1s + "c.txt"
MessageBox.Show(fileName)
Dim ClassStrain As String
ClassStrain = My.Computer.FileSystem.ReadAllText(fileName)
TempLabel3.Text = ClassStrain
Timer1.Start()
--- EDIT --
My bad. I Found the issue to be that there is a skip in text where it goes to a new line. As if i had added vbNewline to it. Is there any way to edit the text file and take away the last character so there isnt a new line.
Use the Trim() function to get rid of white space. Also use Path.Combine() to make sure the path is correctly separated from the filename with the correct number of backslashes:
zoot1s = My.Computer.FileSystem.ReadAllText("zoot1s.txt").Trim()
Dim fileName As String = System.IO.Path.Combine(zoot1s, "c.txt")
I think you just missed the most important thing, which is the whole specific path of your file that will be reading data from, specifically after the ReadAllText() method, so instead of this line:
zoom1s=My.computer.FileSystem.ReadAllText('zoot1s.txt")
You should edit it like this:
zoom1s=My.computer.FileSystem.ReadAllTex(My.Computer.FileSystem.CurrentDirectory & \zoot1s.txt")
I hope this can solve your problem.
^_^

GetLastWriteTime not accurate while files existing

I am trying to get the last modified time for files in a directory. I loop through the directory and print the modified date. The output shows out of 10 files (Did this on other folders too with different number of files). 10 files appeared in the command prompt. All of them printed 12/31/1600.
How could I fix it so that it would print the correct date?
Dim strFilepath = "C:\Test" 'Test folder contains 10 files for test
Dim File As System.IO.FileInfo() = directory.GetFiles()
Dim File1 As System.IO.FileInfo
Dim strLastModified As String
For Each File1 In File 'Loops the GetLastWriteTime
strLastModified = System.IO.File.GetLastWriteTime(strFilepath & File.ToString()).ToShortDateString()
Console.WriteLine(strLastModified)'Prints all 10 files but with the 12/31/1600 date
'Files do exist, code goes into file, it loops through it but wrong date.
Jim gave you already the reason why your date is wron with his link to the dup.
You concat strFilepath and File.ToString() incorrectly because you are missing a backslash \ between them and thus giving something like:
C:\TestYourFile.txt.
Additionally you are using the wrong variable in the For Each.
It should be File1 instead of File (Thanks #Mark).
Solution 1:
That´s the reason why there is the Path.Combine function.
So Change
strLastModified = System.IO.File.GetLastWriteTime(strFilepath & File.ToString()).ToShortDateString()
To
strLastModified = System.IO.File.GetLastWriteTime(Path.Combine(strFilepath, File1.ToString())).ToShortDateString()
Solution 2:
Like Mark commented you could just use the FullName property which makes it even easier:
strLastModified = System.IO.File.GetLastWriteTime(File1.FullName).ToShortDateString()

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.