Skip to content

Files and CSV

Daniele Penza edited this page Dec 5, 2026 · 2 revisions

πŸ“„ Files and CSV

Evidence CSV

πŸ“ Reading a text file

A 6 MB file of 200,000 lines, read into an array of lines:

Method Median Ratio
βœ… Get in Binary mode, then Split(s, vbCrLf) 78 ms 1.0x
Line Input loop 110 ms 1.4x
Input$(LOF(f), f), then Split 166 ms 2.1x
FileSystemObject.ReadAll, then Split 231 ms 3.0x

🟒 Every method reads 6 MB in under a quarter of a second: reading is rarely the bottleneck. Parsing and writing to the sheet usually are.

Public Function ReadAllBytes(ByVal Path As String) As Byte()
    Dim f As Long, b() As Byte
    f = FreeFile
    Open Path For Binary Access Read Shared As #f
    If LOF(f) > 0 Then
        ReDim b(0 To LOF(f) - 1)
        Get #f, , b
    End If
    Close #f
    ReadAllBytes = b
End Function

⚠️ Encoding

Trap πŸ“ Evidence What to do
A UTF-8 file read with Get, Input$ or Line Input One accented letter became two characters: bytes are read as ANSI Decode the bytes with MultiByteToWideChar (below)
ADODB.Stream ReadText on a large file πŸ”΄ 11.3 s for 10 MB, against 16 ms for MultiByteToWideChar (700x) Read the bytes with Get and decode them in one API call
Invalid UTF-8 through ADODB.Stream πŸ”΄ No error, and the text is cut: the bytes 41 C3 28 42 came back as A alone MultiByteToWideChar with MB_ERR_INVALID_CHARS returns 0 and Err.LastDllError = 1113: report the file as invalid
Input$ in Input mode Stops at a Ctrl-Z character Open For Binary and use Get

πŸ“ CSV import and export

Evidence Data

The file has accented names, €, and quoted fields with commas and doubled quotes.

Step ❌ Slow form βœ… Fast form Ratio Fast time
Read and decode ADODB.Stream ReadText: 11.3 s Get + MultiByteToWideChar πŸ”΄ 700x 16 ms
Decode without the API VBA byte loop: 1.1 s MultiByteToWideChar πŸ”΄ 70x 16 ms
Parse into a 2-D array Mid$ per character: 2.5 s InStr jumps (RFC 4180 quotes) 🟠 5.2x 0.52 s
Parse with Split 0.49 s, ❌ wrong on quoted fields InStr jumps 🟒 Split 1.08x faster 0.52 s
Write 5,000 x 8 values Cells(r, c).Value per cell: 1.1 s one Range.Value πŸ”΄ 22x 51 ms
Same, per row Range.Value per row: 0.23 s one Range.Value 🟠 4.4x 51 ms
One write, ScreenUpdating on 76 ms ScreenUpdating off 🟒 1.5x 51 ms
Export 10,000 lines S = S & line: 0.50 s Join, encode, Put 🟠 5.3x 93 ms
Encode the export VBA loop: 122 ms WideCharToMultiByte 🟒 1.3x 93 ms
Encode through ADODB WriteText + SaveToFile: 94 ms WideCharToMultiByte + Put 🟒 1.0x 93 ms

βœ… The whole 10 MB file goes from disk to a 2-D array in about 0.55 s, against about 14 s with ADODB.Stream and a Mid$ parser.

βœ… The import, step by step

  1. Read all bytes at once (ReadAllBytes, above).
  2. Decode UTF-8 in one API call that also rejects invalid bytes (πŸ“ tested in run H):
#If VBA7 Then
    Private Declare PtrSafe Function MultiByteToWideChar Lib "kernel32" (ByVal CodePage As Long, _
        ByVal dwFlags As Long, ByVal lpMultiByteStr As LongPtr, ByVal cbMultiByte As Long, _
        ByVal lpWideCharStr As LongPtr, ByVal cchWideChar As Long) As Long
#Else
    Private Declare Function MultiByteToWideChar Lib "kernel32" (ByVal CodePage As Long, _
        ByVal dwFlags As Long, ByVal lpMultiByteStr As Long, ByVal cbMultiByte As Long, _
        ByVal lpWideCharStr As Long, ByVal cchWideChar As Long) As Long
#End If
Private Const CP_UTF8 As Long = 65001
Private Const MB_ERR_INVALID_CHARS As Long = 8

' Decodes b(First .. First + Count - 1); returns False on invalid UTF-8
' (Err.LastDllError = 1113). Pass First = 3 to skip a byte-order mark.
Public Function DecodeUtf8(ByRef b() As Byte, ByVal First As Long, ByVal Count As Long, _
                           ByRef Text As String) As Boolean
    Dim chars As Long
    Text = vbNullString
    If Count <= 0 Then DecodeUtf8 = True: Exit Function
    chars = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, VarPtr(b(First)), Count, 0, 0)
    If chars = 0 Then Exit Function
    Text = String$(chars, vbNullChar)
    DecodeUtf8 = (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, VarPtr(b(First)), Count, _
                                      StrPtr(Text), chars) = chars)
End Function
  1. Parse by jumping with InStr to the next delimiter, quote or line break, never character by character with Mid$ (πŸ“ 5.2x).
  2. Convert each field to its type in VBA, after checking its format: CDbl follows the system locale (πŸ“ CDbl("1.5") = 15 with an Italian locale); never validate with IsNumeric.
  3. Fill a 2-D array and write it with one Range.Value (πŸ“ 22x per cell), after setting the number format of each column.

Warning

πŸ“ Text written to cells is converted with US rules, whatever the system locale (run H, Italian locale):

Written as text Read back
"2026-11-29" a date
"1234.56" the number 1234.56; shown as 18/05/1903 13:26:24, because the cell kept the date format of the previous value
"1,5" text
"007" 7: leading zeros lost
"1e3" 1000

Write typed values, and set NumberFormat = "@" on text columns (codes, IDs) before writing.

βœ… The export

Collect the lines in a String array, one Join(lines, vbCrLf), encode once, one Put (πŸ“ 5.3x against S = S & line).

#If VBA7 Then
    Private Declare PtrSafe Function WideCharToMultiByte Lib "kernel32" (ByVal CodePage As Long, _
        ByVal dwFlags As Long, ByVal lpWideCharStr As LongPtr, ByVal cchWideChar As Long, _
        ByVal lpMultiByteStr As LongPtr, ByVal cbMultiByte As Long, _
        ByVal lpDefaultChar As LongPtr, ByVal lpUsedDefaultChar As LongPtr) As Long
#Else
    Private Declare Function WideCharToMultiByte Lib "kernel32" (ByVal CodePage As Long, _
        ByVal dwFlags As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long, _
        ByVal lpMultiByteStr As Long, ByVal cbMultiByte As Long, _
        ByVal lpDefaultChar As Long, ByVal lpUsedDefaultChar As Long) As Long
#End If

' UTF-8 bytes of Text, without a byte-order mark.
Public Function EncodeUtf8(ByRef Text As String) As Byte()
    Dim n As Long, b() As Byte
    If Len(Text) > 0 Then
        n = WideCharToMultiByte(CP_UTF8, 0, StrPtr(Text), Len(Text), 0, 0, 0, 0)
        ReDim b(0 To n - 1)
        WideCharToMultiByte CP_UTF8, 0, StrPtr(Text), Len(Text), VarPtr(b(0)), n, 0, 0
    End If
    EncodeUtf8 = b
End Function

🟒 ADODB.Stream is as fast for writing (WriteText + SaveToFile), but it writes a byte-order mark first: remove it if the reader does not expect one.

πŸ“š Choosing a CSV library

Before adopting a ready-made CSV library for VBA, check:

Check Why it matters
Licence A copyleft licence (GPL) obliges a project that includes the code to be GPL too
Size A library of thousands of lines in many classes is hard to audit and to keep in step with your import format
References A dependency on Scripting Runtime, VBScript RegExp or ADO ties the project to those components; ⚠️ VBScript is being retired from Windows
Reading and encoding Some parse only a string already in memory: reading the bytes and decoding UTF-8 is left to the caller (steps 1-2 above)
Upkeep The date of the last update, and whether open issues get answers

βœ… For a project with a defined import format, a reader built on the steps above, with explicit limits and per-row findings, is easier to keep correct than a general library.

⚑ VBA Performance

Topics

Reference

Clone this wiki locally