473,608 Members | 2,565 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Parsing csv file in VB (example included)

I needed to parse a csv file for my project. Could not find any so I
put together this code. It works for general cases. Use it and let me
know. Just
Cut and paste the 2 functions in a new Form and the csv text in
test.csv in the same directory. Watch for the line breaks!

'------ Parse CSV + Demo ----------------------
' (c) Shahid Mahmood (ma*****@alum.r pi.edu)
' ---------------------------------------------
' Parses a csv file and prints results in a debug window
("immediate" ).
' If you know how many fields per line are coming, you can diemnsion
the
' 'strTemp() array accordingly and lost the ReDim ..()
' Handles the case of quoted and un-quoted fields, (only double quoted
"")
' Also handles commas inside a quoted field. DOES not handle embedded
double
' quotes or single quoted fields.
' Enjoy!

Private Sub Form_Load()
Dim fieldArray() As String
Dim i As Integer
Dim lineRead As String
'MsgBox App.Path ' to see where VB is reading from
Open App.Path + "\" + "test.csv" For Input As #1

While Not EOF(1)
Line Input #1, lineRead
fieldArray = parseCsv(lineRe ad)
' Do whatever you want with the array of fields, e.g.
If lineRead <> "" Then For i = 0 To UBound(fieldArr ay):_
Debug.Print fieldArray(i): Next
Wend
End
End Sub

Function parseCsv(lineIn As String) As String()
Dim s As String
Dim local_s As String
Dim n1 As Integer
Dim n2 As Integer
Dim str2 As String
Dim i As Integer
Dim strTemp() As String
i = 0
s = Trim(lineIn) ' remove spaces, if any

While Len(s)
ReDim Preserve strTemp(i) ' Didnt want to have fixed fields,
' dont know how to dynamically allocate, hence ...
If Mid$(s, 1, 1) = """" Then ' if already in quotes ...
strTemp(i) = Mid$(s, 2, InStr(2, s, """") - 2)'find 2nd ""
Else
If InStr(s, ",") Then strTemp(i) = Mid$(s, 1, InStr(s, ",") -
1)
End If
's = Mid$(s, Len(strTemp(i)) + 1)
n2 = InStr(Len(strTe mp(i)) Or 1, s, ",")
If n2 Then s = Trim(Mid$(s, n2 + 1)) Else s = "" ' clip till next
i = i + 1
Wend
parseCsv = strTemp
End Function
'---- END -------

Sample test.csv
---------------
"Hello, World", wow, " asdasd asdasd"
"Hello1, World1", wow1, " asdasd1 asdasd1"
"Hello2, World2", wow2, " asdasd2 asdasd2"
"This is Field1", "Field2",Field3 ,"Field4",field 5,field6, "Field7,8,9 "
Jul 17 '05 #1
0 24097

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2628
by: Viktor Rosenfeld | last post by:
Hi, I need to create a parser for a Python project, and I'd like to use process kinda like lex/yacc. I've looked at various parsing packages online, but didn't find anything useful for me: - PyLR seems promising but is for Python 1.5 - Yappy seems promising, but I couldn't get it to work. It doesn't even compile the main example in it's documentation - mxTexttools is way complicated. I'd like something that I can give a BNF
4
1832
by: ArmedCoder | last post by:
Ok, i have this problem that is driving me nuts! I have a header file that has the function definition: landindp get_world_landind( worldp world ); where landindp and worldp are pointers to structs. I keep getting errors saying "parse error before get_world_landind()" and "warning: data definition has no type or storage class" Now i have the landind.h file included, and landindp is defined as: typedef struct landind *landindp;
6
2066
by: Tuomas Rannikko | last post by:
Hello, I'm currently writing a XML processor for the fun of it. There is something I don't understand in the spec though. I'm obviously missing something important. The spec states that both Internal General and Character references are included when referenced in content. And "included" means: <quote>
4
4852
by: Rick Walsh | last post by:
I have an HTML table in the following format: <table> <tr><td>Header 1</td><td>Header 2</td></tr> <tr><td>1</td><td>2</td></tr> <tr><td>3</td><td>4</td></tr> <tr><td>5</td><td>6</td></tr> </table> With an XSLT styles sheet, I can use for-each to grab the values in
9
4052
by: ankitdesai | last post by:
I would like to parse a couple of tables within an individual player's SHTML page. For example, I would like to get the "Actual Pitching Statistics" and the "Translated Pitching Statistics" portions of Babe Ruth page (http://www.baseballprospectus.com/dt/ruthba01.shtml) and store that info in a CSV file. Also, I would like to do this for numerous players whose IDs I have stored in a text file (e.g.: cobbty01, ruthba01, speaktr01, etc.)....
3
4372
by: toton | last post by:
Hi, I have some ascii files, which are having some formatted text. I want to read some section only from the total file. For that what I am doing is indexing the sections (denoted by .START in the file) with the location. And for a particular section I parse only that section. The file is something like, .... DATAS
3
3307
by: Anup Daware | last post by:
Hi Group, I am facing a strange problem here: I am trying to read xml response from a servlet using XmlTextWriter. I am able to read the read half of the xml and suddenly an exception: “Unexpected end of file while parsing Name has occurred” isbeing thrown. Following is the part o xml I am trying to read: <CHECK_ITEM_OUT>
18
2827
by: Steven Borrelli | last post by:
Hello, I am using the <?php include() ?statement on my website for organizational purposes. However, one of my includes contains some PHP code. Is there any way for the server to actually parse the include? I've tried this before, and it did not parse the include. Rather, it included the file as just plain ASCII. ======================= /*EXAMPLE 1*/ /*index.php*/
13
4484
by: Chris Carlen | last post by:
Hi: Having completed enough serial driver code for a TMS320F2812 microcontroller to talk to a terminal, I am now trying different approaches to command interpretation. I have a very simple command set consisting of several single letter commands which take no arguments. A few additional single letter commands take arguments:
2
2583
by: python | last post by:
I'm parsing a text file for a proprietary product that has the following 2 directives: #include <somefile> #define <name<value> Defined constants are referenced via <#name#syntax. I'm looking for a single text stream that results from processing a file containing these directives. Even better would be an iterator(?) type
0
8057
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8491
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8142
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8329
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6010
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 presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5475
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3959
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4022
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1327
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.