Export to a text file with quoted fields

Export to a text file with quoted fields

As explained in another item in this Tip Bank, you can use the Recordset’s GetString method to export a Recordset to a comma-delimited or tab-delimited text file. However, if you are exporting string fields that might include commas or tabs, you should include the fields’ value within quotes. At a first glance, this seems to rule out the GetString method, but you can resort to the following trick:

Dim rs As New ADODB.Recordset, tmp As Stringrs.Open "authors", "DSN=pubs", adOpenForwardOnly, , adCmdTableOpen "c:authors.dat" For Output As #1' output the opening quotes for the first' field of the first rowPrint #1, """"' output the rest of the recordsetDo Until rs.EOF    ' blocks of 100 rows each    tmp = rs.GetString(, 100, """,""", """" & vbCrLf & """", "")    If rs.EOF Then        ' drop the double quote char printed in excess        tmp = Left$(tmp, Len(tmp) - 1)    End If    Print #1, tmp;LoopClose #1

Unfortunately, you can’t decide which fields are to be quoted, so this is an all-or-nothing decision.

See also  How IoT Tech Will Transform Logistics

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist