473,387 Members | 1,529 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

I am working on an Excel VBA Application that Imports

Hello,
I am working on an Excel VBA Application that imports A CSV file every 2 minutes. Right before it imports the program clears sheet1 and then imports the Data. The CSV file is updated every 2 minutes as well. The file name changes daily, so here is my problem I want to be able to import automatically every day every two minutes. I have everything working except the automatic import with the auto name finding. The part of the program that I am stuck on is listed below. The way I need it to work is to import the "Availability" this has pulled in all the information from the file Path.
Any help you can give me would be appreciated
Thanks
Dwight


Expand|Select|Wrap|Line Numbers
  1.  
  2. Dim myDir As String, fn As String, a(), n As Long, Availability As String
  3. Dim myDate As Date, temp As Date
  4. Private Sub Import()
  5.  
  6.  
  7. myDir = "Q:\Manufacturing\Equipment\DispatchLogs\logs\7-DES\"
  8. fn = Dir(myDir & "\*.csv")
  9.  
  10.  
  11. Do While fn <> ""
  12.     temp = CreateObject("Scripting.FileSystemObject").Getfile(myDir & "\" & fn).DateLastModified
  13.     If myDate = 0 Then
  14.         myDate = temp: Availability = myDir & "\" & fn
  15.     Else
  16.         If myDate < temp Then myDate = temp: Availability = myDir & "\" & fn
  17.     End If
  18.     fn = Dir
  19. Loop
  20. If Len(Availability) Then
  21.       If vbYes = MsgBox("Opening Availability File  Name : " & Availability & vbLf & _
  22.     "Last modified on : " & myDate, vbYesNo) Then
  23.  
  24.  
  25.  
  26.     End If
  27.  
  28. End Sub
  29.  
Apr 14 '14 #1
6 1823
zmbd
5,501 Expert Mod 4TB
So what exactly is wrong with your code?

Posting code that appears to have had very little if any troubleshooting performed, and expecting someone to help doesn't usually result in much of an answer and may result in your thread being deleted.

Instead, please tell us what you were expecting to happen, what actually happened, for each error: the EXACT title, error number, and descriptions that occurred and at what line in your posted code the error occurred. These are the minimum requirements for posting a question of this nature.

You tell us nothing about how the file names are created.

You also tell us nothing about how the target directory is being used: are there other files being dumped into the folder, do you need to keep the orginal files, etc...?

for example, I have a LIMS database that goes out to our network, there is a single directory where pH-Meters and other instruements dump generic text files. Only the content of the files matter; thus, I pull the current file names into an array, parse the names from the array to the import function that opens and imports the file contents... because we have to keep the original data, the script then moves the old file out of the dump directory to an archive directory... does this every 2 minutes, or whenever it finishes parsing the current array - which ever is the latter of the two.
Apr 14 '14 #2
There are no errors, the program is incomplete.If you look on line 16 you will see (If myDate < temp Then myDate = temp: Availability = myDir & "\" & fn)This part of the program pulls all the information about the directory and the file name for the day and store the information in (Availability)
I dont know how to write the code that will Import (Availability)
Thanks
Dwight
Apr 15 '14 #3
zmbd
5,501 Expert Mod 4TB
If you look on line 16
and you define
Expand|Select|Wrap|Line Numbers
  1. fn = Dir(myDir & "\*.csv")
earlier in the code.
What happens when there are two or more files in the directory, this code will most likely fail to function as expected.

Also
Expand|Select|Wrap|Line Numbers
  1. If myDate < temp Then myDate = temp: Availability = myDir & "\" & fn
  2.  
although allowed would be better written:
Expand|Select|Wrap|Line Numbers
  1.    If myDate < temp Then 
  2.       myDate = temp
  3.       Availability = myDir & "\" & fn
  4.    EndIf
Having two commands per line doesn't help the parser,
is harder to troubleshoot, easily missed by anyone that follows you to maintain the code, and overall detracts from readability of the code.

the program is incomplete
Very well aware of that... it didn't take me more than a quick glance to determine that your code wasn't quite right.
You also left out quite a bit of detail that I asked for in my last post, and even gave you an example to show the importance of having that information.

I dont know how to write the code that will Import (Availability)
Start with this link: DoCmd.TransferText Method (Access/Office 2010) - ignore the example about the word mail-merge at the bottom of this link... who knows why that is there as it has nothing to do with the method.

I have also used the basic IO methods to read the files in line by line and write directly to the open recordset: VBA Standard Text File I/O Statements

We can help you to correct errors, clear-up theory and application, and can/will even show you some of the more esoteric methods – some of these are readily available in our Insights Articles ( Microsoft Access / VBA Insights Sitemap ); however, we do ask that you write the code or design the project first. (^_^)
Apr 15 '14 #4
Thanks for your Help, I will look through these and reply with what I find.
Thanks
Dwight
Apr 15 '14 #5
Ok so here is what I have found so far:


Expand|Select|Wrap|Line Numbers
  1. Dim myDir As String, fn As String, a(), n As Long, Availability As String
  2. Dim myDate As Date, temp As Date
  3. Sub Import()
  4.  
  5.  
  6. myDir = "Q:\Manufacturing\Equipment\DispatchLogs\logs\7-DES\"
  7. fn = Dir(myDir & "\*.csv")
  8.  
  9.  
  10. Do While fn <> ""
  11.     temp = CreateObject("Scripting.FileSystemObject").Getfile(myDir & "\" & fn).DateLastModified
  12.     If myDate = 0 Then
  13.         myDate = temp: Availability = myDir & "\" & fn
  14.     Else
  15.         If myDate < temp Then 
  16.         myDate = temp: 
  17.         Availability = myDir & "\" & fn
  18.     End If
  19.     fn = Dir
  20. Loop
  21. If Len(Availability) Then
  22.       If vbYes = MsgBox("Opening Availability File  Name : " & Availability & vbLf & _
  23.     "Last modified on : " & myDate, vbYesNo) Then
  24.  
  25.    DoCmd.TransferText acImportDelim, "", "Sheet1", "Availability", True, ""
  26.     End If
  27. End If
  28.  
  29. End Sub
  30.  
now I am getting a run-time error 2046
The Command or Action "TransferText" isn't available now.
I have tried several different way of writing this code with no luck.
The last statement should import a CSV file (Line 6) from the above directory using the Variable "Availability",
Well that is what I need it to do.
Thanks
Dwight
Apr 18 '14 #6
zmbd
5,501 Expert Mod 4TB
Sorry, the docmd is an Access method not for Excel.

To make up for my mistake, try the following as a model,
Using the In Excel2010 you can make use of the QueryTable method which makes the importing of data slick. You'll need this as a reference: _QueryTable Properties (OFF2010)

I used a tab delimited csv text file with double quotes as the string demark.... the following should be fairly self explanatory.

Expand|Select|Wrap|Line Numbers
  1. Option Explicit
  2. Sub ImportTextFileToWorksheet()
  3. '
  4. '
  5.     Dim zstrFile As String
  6.     '
  7.     zstrFile = "TEXT;C:\Users\a109077\Documents\Working.csv"
  8.     '
  9.     With ActiveSheet.QueryTables _
  10.         .Add _
  11.         (Connection:=zstrFile, _
  12.             Destination:=Range("$A$1"))
  13.         .Name = "ztempImport"
  14.         .FieldNames = True
  15.         .RowNumbers = False
  16.         .FillAdjacentFormulas = False
  17.         .PreserveFormatting = True
  18.         .RefreshOnFileOpen = False
  19.         .RefreshStyle = xlInsertDeleteCells
  20.         .SavePassword = False
  21.         .SaveData = True
  22.         .AdjustColumnWidth = True
  23.         .RefreshPeriod = 0
  24.         .TextFilePromptOnRefresh = False
  25.         .TextFilePlatform = 437
  26.         .TextFileStartRow = 1
  27.         .TextFileParseType = xlDelimited
  28.         .TextFileTextQualifier = xlTextQualifierDoubleQuote
  29.         .TextFileConsecutiveDelimiter = False
  30.         .TextFileTabDelimiter = True
  31.         .TextFileSemicolonDelimiter = False
  32.         .TextFileCommaDelimiter = False
  33.         .TextFileSpaceDelimiter = False
  34.         .TextFileColumnDataTypes = Array(1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
  35.         .TextFileTrailingMinusNumbers = True
  36.         .Refresh BackgroundQuery:=False
  37.     End With
  38.     ActiveSheet.QueryTables.Item("ztempImport_1").Delete
  39. End Sub
  40.  
SO, what I did was open a connection to the file, as I would any other datasource, save the data to the worksheet setting things as I go...

NOTE: I BUILD THE CONNECTION STRING FIRST:
zstrFile = "TEXT;C:\Users\a109077\Documents\Working.csv"

This allows me to debug the string incase something gets mucked-up... and (IMHO) will be what you should do to build your files' path too,

Line #35: TextFileColumnDataTypes
I use the actual numeric here, easy enough to find, just <ctrl><g> and type ?xlSkipColumn which would yeld a 9, in the array I used, there is a "3" for "D/M/Y" date formated coulmn.
I highly advise you to use the type casting as I have in line35 to help ensure that your data is the proper type. If I could set the numeric type I would... and that "9" is very useful if you have a few columns of data you don't want to pull in!

For the very last line (line#39), I actually remove the connection to the outside file; thus, there should be no refresh errors or connection prompts etc...
NOTE: The name on line# 14.... note the item name in the last line of code... so, if you ran this code three times using "qryname" in line#14 you could have qryname_1, qryname_2, qryname_3, etc... so to remove them you have to either do a for/all/in-collection or append the correct count as I did to the name you give the querytable.

This is part of a code that I do use to handle some data imports... (that's where the array actually comes from in line 35 (^_^)) I've removed the error trapping and the other sensitive information; however, so long as you refere to a valid text file and change the array in 35 to match your file, this code will work.

Once again, sorry, I was on automatic for Access.
Apr 18 '14 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: ST | last post by:
Hi, I'm having problems opening up excel thru my code. It will write and saveas an excel file, but the application won't open on the user's computer, excel seems to be hidden, because it shows up...
5
by: KC | last post by:
Hi, I have code similar to this.. Dim xlApp As Object xlApp = CreateObject("Excel.Application", "\\MyServer") The call is from a asp.net (Intranet) application. \\Myserver is a network...
8
by: ChrisBowringGG | last post by:
When you use Application.Quit() on an Excel application, there can still be an instance of Excel running, as seen in Task Manager. You can try following the advice on MSDN: ...
0
by: Fabrizio | last post by:
Hi, i'm tryng to build a ASP.net application that reads from an excel file . I'm using the microsoft Excel 10.0 object library and office interop 10 library Everything was ok untill 2 days ago...
1
by: Bernd Muent | last post by:
Hi together, I am using the following code in Visual Basic to open Word or Excel applications: Word: Dim w As Word.Application w = CType(CreateObject("Word.application"), Word.Application)...
1
by: Ultima | last post by:
I'm trying to create an Excel file using a VB program. I have added the reference to Excel Object Library yet when I try to compile it, I get an error at the line exc_app =...
9
by: Doug Glancy | last post by:
I got the following code from Francesco Balena's site, for disposing of Com objects: Sub SetNothing(Of T)(ByRef obj As T) ' Dispose of the object if possible If obj IsNot Nothing AndAlso...
2
by: RohitGBhagwat | last post by:
Hi, I am New To ASP.Net and I have created a small application in ASP.Net using C# which is a reporting Tool. In this Application I have to Edit an Excel File on a Weekly basis and for that i am...
1
by: prakashsakthivel | last post by:
Hi Members, One excel application (Excel 2003), I set range, formating it is working fine through macro.. After that as per client requirements, I changed Excel 2000 instead of Excel 2003....
1
by: Paul Morriss | last post by:
I have an application that opens a Excel file into a form using AxWebBrowser.Navigate. This works fine unless there is another Excel file open before I run the application, in which both excel files...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.