Monday, December 31, 2018

excel - Parse CSV, ignoring commas inside string literals in VBA?



I have a VBA application that runs every day. It checks a folder where CSVs are downloaded automatically, and adds their contents to a database. When parsing them, I realized that certain values had commas as a part of their name. These values were contained in string literals.



So I'm trying to figure out how to parse this CSV and ignore commas that are contained in string literals. For example...



1,2,3,"This should,be one part",5,6,7 Should return 

1

2
3
"This should,be one part"
5
6
7


I have been using VBA's split() function, because I don't wanna reinvent the wheel, but if I have to I guess I'll do something else.




Any suggestions would be appreciated.


Answer



A simple regex for parsing a CSV line, assuming no quotes inside quoted fields, is:



"[^"]*"|[^,]*


Each match will return a field.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...