473,406 Members | 2,439 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,406 software developers and data experts.

VBA for importing a formatted txt file

Uncle Dickie
Hi All,

I am trying to bring a text file in to an Access table using VBA.

My problem is that the generated text file has a mixture of delimited and non-delimited data and I can't seem to work out how to use the Import Wizard to save a particular format and then use it with
Expand|Select|Wrap|Line Numbers
  1. DoCmd.TransferText acImportDelim, "MySavedFormat", "TableName", "C:\File.txt", True
Maybe that is not even the right way of going about it.

An example of the text file is as follows:
Expand|Select|Wrap|Line Numbers
  1. <Sensor Name>Name
  2. <Sensor ID>123
  3. <Sample Rate>10
  4. <Scale>C
  5. time,temperature,sample
  6. 01/01/01 10:00,20,1
  7. 01/01/01 10:30,21,2
  8. 01/01/01 11:00,20,3
And I would like a table in the form:
Expand|Select|Wrap|Line Numbers
  1. SensorID  Scale  time,           temperature  sample
  2. 123       C      01/01/01 10:00  20           1
  3. 123       C      01/01/01 10:30  21           2
  4. 123       C      01/01/01 11:00  20           3
Any pointers would be very much appreciated.

Richard
Mar 13 '13 #1
6 5219
zmbd
5,501 Expert Mod 4TB
Uncle Dickie:
From what you have listed, the import via the wizards will not work.
Is this a dot-TXT type file?
If so then you can open the file for import and read the lines in and parse them.
The basics would be here:File I/O Using VBA

Once you have the file open, you can then read the line in, use the string functions to determine the headers and then parce the remaining.

Have you tried any vba yet?
If so, would you post your work?
Mar 13 '13 #2
Thanks for the pointer.
I have not tried anything other than the TransferText function of my original post but I will now go through the File I/O parsing and see where I get. Once I have made some progress (or not!) I will post again.
Mar 13 '13 #3
zmbd
5,501 Expert Mod 4TB
YEA!
I look forward to helping you do this... should be fairly straight forward once you get the file open, a loop, a select or if-then, and maybe a split (?).
If you do need to post back, please let us know which version of Access you are using as there are somethings you can do in the new versions and not in the older.
Mar 13 '13 #4
Thanks ZMBD!

I am getting somewhere now, although not with your suggestion...

I have found another reference to using Microsoft Scripting Runtime and have been working through something with that (as below). Does that seem like a sensible route to follow or should I go back to your suggestion of 'Open x For Input'?

I must confess I got confused reading your link so haven't tried it, but then I got confused reading up on this solution as well and it wasn't until I tried it that it clicked so I am still happy to change tack if it seems more logical.

My code so far is:
Expand|Select|Wrap|Line Numbers
  1. 'Need to ensure that Microsoft Scripting Runtime is enabled from the Tools, References menu
  2.  
  3.     Dim myFileName As String
  4.     Dim myID As String
  5.     Dim myScale As String
  6.  
  7.     myFileName = "C:\Instrument1_20.wdf"
  8.  
  9.     With New Scripting.FileSystemObject
  10.         With .OpenTextFile(myFileName, ForReading)
  11.             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 1
  12.             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 2
  13.             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 3
  14.             If Not .AtEndOfStream Then myID = .ReadLine         'Line 4 is Sensor ID
  15.             myID = (Mid(myID, InStr(myID, ">") + 1))            'Remove the leading text
  16.             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 5
  17.             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 6
  18.             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 7
  19.             If Not .AtEndOfStream Then myScale = .ReadLine      'Line 8 is Scale
  20.             myScale = (Mid(myScale, InStr(myScale, ">") + 1))   'Remove the leading text
  21.             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 9
  22.             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 10
  23.             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 11
  24.  
  25. '            MsgBox (myID + " " + myScale)
  26.  
  27. '            Do Until .AtEndOfStream
  28. '                MsgBox (.ReadLine)
  29. '            Loop
  30.         End With
  31.     End With
This has got me beyond the 'header' info in the file and I am intending to use the Do Until Loop to split the remaining lines of actual data in to an array.

I would then populate a table with myID, myScale and each entry in the array.

(Haven't worked out how to append the info to a table yet!)

BTW I am using Access 2003 but I am writing this for a specific company and I don't know what they are using yet so I may have to change a couple of things...
Mar 13 '13 #5
zmbd
5,501 Expert Mod 4TB
You can use either what I've posted you to, or you can use the scripting as you've started to do; however, I prefer the method I linked you to in that it is native to the VBA code therefor does not require any additional library references.
I'm in one of my remote labs that doesn't have access installed for a short while today so I'll have to take a look at your code a tad bit later; hwoever, I know that Rabbit, NeoPa, and ADezii will be around shortly and can fix you up too...

As for suggestions - as a air-code:
Starting on line 11
Start a do while loop checking for the end of string
Read your line
Parse the first charactor in the string
select case statements
check for the "<" if found then find the the value you're after
check for the "t" and discard etc...
Check for numeric... then use the split function against the string and parse.
have a default case to either throw an error or somehting.
loop back...

the way you have it coded now, if there's any corruption within the file, missing lines, added lines, etc... you will not have any usuable information.
Mar 13 '13 #6
Thanks again. I have something working (with absolutely no error trapping as you mentioned) as follows:

Expand|Select|Wrap|Line Numbers
  1.     'Need to ensure that Microsoft Scripting Runtime is enabled from the Tools, References menu
  2.  
  3.     DoCmd.SetWarnings False
  4.  
  5.  
  6.     Dim myDirectory As String
  7.     Dim myFile As File
  8. '    Dim myFileCount As Integer
  9.  
  10.     Dim myFileName As String
  11.     Dim myID As String
  12.     Dim myScale As String
  13.     Dim myValues() As String
  14.     Dim myReadingNumber As Integer
  15.     Dim i As Integer
  16.     Dim myDate As String
  17.     Dim myReading As Single
  18.  
  19.     myDirectory = "\\Lasfs01\win_apps\ENG\TEMP\Richard\WiFi Trial"
  20.  
  21.     With New Scripting.FileSystemObject
  22.         With .GetFolder(myDirectory)
  23.             For Each myFile In .Files
  24.                 If LCase(Right(myFile.Name, 4)) = ".wdf" Then
  25.                     myFileName = myDirectory & "\" & myFile.Name
  26.  
  27.                     With New Scripting.FileSystemObject
  28.                         With .OpenTextFile(myFileName, ForReading)
  29.                             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 1
  30.                             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 2
  31.                             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 3
  32.                             If Not .AtEndOfStream Then myID = .ReadLine         'Line 4 is Sensor ID
  33.                             myID = (Mid(myID, InStr(myID, ">") + 1))            'Remove the leading text
  34.                             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 5
  35.                             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 6
  36.                             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 7
  37.                             If Not .AtEndOfStream Then myScale = .ReadLine      'Line 8 is Scale
  38.                             myScale = (Mid(myScale, InStr(myScale, ">") + 1))   'Remove the leading text
  39.                             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 9
  40.                             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 10
  41.                             If Not .AtEndOfStream Then .SkipLine                'Don't need Line 11
  42.  
  43.                             i = 0
  44.  
  45.                             Do Until .AtEndOfStream
  46.                                 myValues = Split(.ReadLine, ",")
  47.                                 myReadingNumber = myValues(3) + i
  48.                                 i = i + 1
  49.                                 myDateArray = Split(Left(myValues(0), 10), "-")
  50.                                 myTimeArray = Split(Trim(Mid(myValues(0), 11)), ":")
  51.                                 myDate = myValues(0)
  52.                                 myReading = myValues(1)
  53.  
  54.                                 DoCmd.RunSQL "INSERT INTO DestTable (SensorID, TempScale, SampleNumber, [Time], Temperature) VALUES ('" & myID & "', '" & myScale & "', " & myReadingNumber & ", #" & myDate & "#, " & myReading & ");"
  55.                             Loop
  56.                         End With
  57.                     End With
  58.  
  59.                     With New Scripting.FileSystemObject
  60.                         If .FileExists(myFileName) Then
  61.                             .DeleteFile myFileName
  62.                         End If
  63.                     End With
  64.  
  65.                 End If
  66.             Next
  67.         End With
  68.     End With
  69.  
  70.     DoCmd.SetWarnings True
I am now spent for the day but I will go back tomorrow and have a look at doing it the way you originally said as I fully take your point about additional libraries. Either way I'll also put in some error trapping and case statements as you suggest to try and make it robust!

You might notice in the above (complete) code that it actually checks a directory for all .wdf files and then brings data in from each one before deleting the file. The application I am dealing with is a bunch of sensors periodically sending packets of their data as a wdf file. A user has asked that these get concatenated in to a database from which they can do any form of data manipulation and Access was their choice.
Mar 13 '13 #7

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

Similar topics

11
by: Grim Reaper | last post by:
I am importing a .csv file into Access that has 37 fields. My problem is that sometimes the last field only has data at the end of the column (it looks like when you import a file into Access, for...
12
by: Jonathan | last post by:
How do you tell the .csv file that you are to import that it has no row headers as I went to the web site http://www.connectionstrings.com/ and under text file it says: "HDR=Yes;" indicates that...
6
by: mesterak | last post by:
I have some log files I need to process via VB.NET and C# based applications. I read the entire contents of each file individually into a string variable using the StreamReader class (.ReadToEnd). ...
0
by: Mike Collins | last post by:
I am trying to export data from multiple tables in SQL Server to an XML file so I can then import it to another database. It seems to be working fine for exporting, but I am having trouble...
5
by: Mike Collins | last post by:
I am trying to export data from multiple tables in SQL Server to an XML file so I can then import it to another database. It seems to be working fine for exporting, but I am having trouble...
1
by: Alan | last post by:
OK this is a weird one. I've got an import routine going whereby name and address data is pulled into a table from a csv file. I'm having strange results when importing postcode/zip data into...
1
by: lenniekuah | last post by:
I have written a VB6 program extracting Customers Name and address from a table to incorporate it into a letter and output it to MS WORDS. At the bottom of the letter I tried to insert a digitised...
3
by: gulllet | last post by:
I try to import a tab separated text file into sql server 2005 using the import guide. But when running the job I get the error message Error 0xc02020c5: Data Flow Task: Data conversion failed...
0
by: raka61 | last post by:
Hi , I need help in understanding if i can directly(there are 100s of different structured files i get in text format with & hence dont wnat to manually define the structure for each file...
2
by: vipin2608 | last post by:
Hi.. I have import statement in a JSP...and importing a class file located in a JAR....but when I run that JSP it show error Package does not exist..... I have put a JAR file in proper location...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.