Skip to main content

— Transparency

What the Excel workbook macro does

The standalone Excel workbook contains a VBA macro: it's what regenerates your XML when you click "Generate XML". Here is what it does, what it never does and how to check it — everything your IT department may ask about, too.

In short

It reads the workbook

The "Data" sheet (except row 2, your labels, which it ignores) and the structure information stored in the workbook. Nothing else on your computer.

It writes a single file

The XML, where and under the name you choose. While writing, a temporary file is created next to it, then renamed: an existing XML is never damaged if something goes wrong.

Offline

No connection to the Internet or to our servers, no usage tracking. Generation works without a network.

Readable by anyone

The code isn't password-protected: you can review it in Excel, and it's published in full below.

What it never does

Before it goes into the workbooks, every version of the code goes through our automated tests: they fail if any of the instructions below appears in it.

  • Connect to the Internet

    No network call: the macro can neither send nor receive data.

    XMLHTTPWinHttpFollowHyperlink

  • Start on its own

    Nothing runs when the workbook opens: the macro only starts when you click the button.

    Auto_OpenWorkbook_OpenAuto_CloseOnTime

  • Launch programs

    No system command, no external script, no simulated keystrokes.

    ShellMacScriptAppleScriptTaskSendKeysApplication.RunCallByNameEvaluateExecuteExcel4MacroDDEInitiateWorkbooks.Open

  • Call Windows or macOS directly

    No system function declaration: the macro only uses the VBA language and Excel's own functions.

    Declare

  • Use external components

    No COM or ActiveX object, no file-system or database library.

    CreateObjectGetObjectADODBScripting.

Why Windows blocks the workbook

Since 2022, Microsoft blocks macros by default in any file downloaded from the Internet: that's the "Security risk" banner. It's a good protection, and we'll never ask you to turn it off.

Only unblock a workbook whose origin you know — the one you've just generated on excelifyxml.com: right-click the file › Properties › tick "Unblock". Never enable all macros in Excel's settings.

Guide: unblock an Excel file safely

Check it yourself

  1. 1Open the workbook. If Excel opens it in Protected View, click "Enable Editing": there's no need to enable macros to read their code.
  2. 2Open the Visual Basic editor: Alt+F11 on Windows, Tools › Macro › Visual Basic Editor on Mac.
  3. 3The modules are listed on the left, under "VBAProject". Double-click a module to read its code and compare it with the one published below.

Source code

Here is the full code of the macro shipped in the workbooks, module by module.

modExfBuild.basRebuilding the XML (2/4): rows grouped and checked, before anything is written809 lines
Attribute VB_Name = "modExfBuild"
' ExcelifyXML - the reconstruction engine, part 2: rows grouped under their
' wrapper instances, then the element tree built row by row. Port of the rest
' of executePlan in src/lib/excel-macro/engine/execute.ts (columns and rows:
' modExfEngine; the tree: modExfTree; the output: modExfWrite).
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary
Option Private Module

' The value repairs of a row (execute.ts rowRepairsOf), set by ExfBuildRepairTables.
Private mColEaStart() As Long           ' by COL entry: its empty-attribute elements in EAUNDER
Private mColEaCount() As Long
Private mColTrStart() As Long           ' by COL entry: its text-required elements in TRUNDER
Private mColTrCount() As Long
Private mEaU() As Long                  ' EMPTYATTR entries: their unique column, -1 absent
Private mTrU() As Long                  ' TEXTREQ entries: their unique column, -1 absent
Private mEaHeld() As Long               ' by element: the row (n + 1) that holds it
Private mTrHeld() As Long
Private mEaWrite() As Long              ' by unique column: the row (n + 1) that writes it empty
Private mEaThrough() As Long            ' the unique columns whose path goes through such an element
Private mEaThroughCount As Long
Private mTrThrough() As Long
Private mTrThroughCount As Long
Private mCleaned As ExfStrMap           ' "row:column" of the cells the clean-up left empty
Private mAnyCleaned As Boolean
Private mLeftOut() As Boolean           ' by unique name: filled cells left out (askCellsIgnored)
Private mRenamedHit() As Boolean        ' by unique name: a renamed header with filled cells

' Every refusal of the engine happens here, before any file is written.
Public Function ExfEngineBuild(ByRef p As ExfPlan) As Boolean
    Dim u As Long, n As Long, i As Long, j As Long, k As Long, t As Long, g As Long
    Dim v As String, acc As String, sig As String, levels As Long, grpCount As Long, root As Long
    Dim keyU() As Long, own() As String, levelKey() As String
    Dim groupIndex As ExfStrMap, grpKeys() As String, grpVals() As String, grpFirst() As Long, grpLast() As Long, rowNext() As Long
    Dim isSelf() As Boolean, instanceIndex As ExfStrMap, knownTypes() As String, typeList As String
    Dim typeMap As ExfStrMap, allowed() As Boolean, isTypeCol() As Boolean, typeU As Long
    Dim uniqNameId() As Long, keyOrder() As Long, keyLen() As String
    Dim newColumn() As Boolean, attrWritten() As Boolean
    Dim cursor As Long, wrapper As Long, rowNode As Long, leaf As Long, tagId As Long, rowType As Long
    Dim scoped As Boolean, outOfType As Boolean
    Dim aftParent() As Long, aftKind() As Long, aftStart() As Long, aftCount() As Long, aftTotal As Long
    Dim rowGrp() As Long, rankIndex As ExfStrMap, rowRank() As Long, rankStart() As Long, sortedRows() As Long
    Dim total As Long, cnt As Long, w As Long, writeU() As Long, byCol() As Long, rowTypeOf() As Long
    Dim stamp As Long

    If Not ExfEngineCheckColumns() Then Exit Function

    ' --- Row types, and the columns each one keeps
    ReDim knownTypes(0 To p.typeCount)
    For t = 0 To p.typeCount - 1
        knownTypes(t) = p.strs(p.types(t))
        If t > 0 Then typeList = typeList & ", "
        typeList = typeList & knownTypes(t)
    Next t
    ' allowed(t, u): column u is written for rows of type t.
    ReDim allowed(0 To p.typeCount, 0 To gUniqCount)
    For t = 0 To p.typeCount - 1
        ExfMapInit typeMap, p.typeColCount(t)
        For k = p.typeColStart(t) To p.typeColStart(t) + p.typeColCount(t) - 1
            ExfMapSet typeMap, p.strs(p.typeCols(k)), 1
        Next k
        For u = 0 To gUniqCount - 1
            allowed(t, u) = ExfMapGet(typeMap, gUniqName(u)) >= 0
            ' A renamed header is a column of its source's types (value-repairs.ts withRenamedTypes).
            If Not allowed(t, u) Then
                If gUniqRenamed(u) >= 0 Then allowed(t, u) = ExfMapGet(typeMap, p.strs(p.colName(gUniqRenamed(u)))) >= 0
            End If
        Next u
    Next t
    typeU = ExfMapGet(gUniqIndex, "_type")
    ' Each kept row's type (its trimmed _type, as the site reads it), -1 unknown.
    ReDim rowTypeOf(0 To gRowCount)
    For n = 0 To gRowCount - 1
        rowTypeOf(n) = -1
        If p.isMultiTag And typeU >= 0 Then
            v = ExfTrim(gVals(typeU, n), gIsSpace)
            For t = 0 To p.typeCount - 1
                If knownTypes(t) = v Then
                    rowTypeOf(n) = t
                    Exit For
                End If
            Next t
        End If
    Next n

    ' --- The site's stops, on the same cells: what the XML can't hold, then
    ' the characters it forbids (cleaned here). Asked by ExfRunBook.
    ExfBuildFindCells p, rowTypeOf, allowed, knownTypes, typeU
    ' Leading zeros put back, true / false in the source's spelling, then the
    ' older boolean repair, which only takes the columns these leave.
    ExfEngineLoadCase p
    ExfEngineRepairValues p
    ExfEngineNormalizeBooleans p

    ' --- Group rows by wrapper instance (wrappers.ts wrapperKeyOf), in order
    ' of first appearance. keyU: -2 = fixed value, -1 = column absent, else the
    ' unique column holding the value.
    levels = p.wrapCount
    ReDim keyU(0 To p.keyCount)
    For k = 0 To p.keyCount - 1
        If p.keyColumn(k) >= 0 Then
            keyU(k) = ExfMapGet(gUniqIndex, p.strs(p.keyColumn(k)))
        Else
            keyU(k) = -2
        End If
    Next k
    ReDim own(0 To p.keyCount)
    ReDim levelKey(0 To levels)
    ReDim grpKeys(0 To levels, 0 To gRowCount)
    ReDim grpVals(0 To p.keyCount, 0 To gRowCount)
    ReDim grpFirst(0 To gRowCount)
    ReDim grpLast(0 To gRowCount)
    ReDim rowNext(0 To gRowCount)
    ReDim rowGrp(0 To gRowCount)
    ExfMapInit groupIndex, 64
    For n = 0 To gRowCount - 1
        acc = vbNullString
        For i = 0 To levels - 1
            For k = p.wrapKeyStart(i) To p.wrapKeyStart(i) + p.wrapKeyCount(i) - 1
                If keyU(k) = -2 Then
                    own(k) = p.strs(p.keyDefault(k))
                ElseIf keyU(k) >= 0 Then
                    own(k) = gVals(keyU(k), n)
                Else
                    own(k) = vbNullString
                End If
                acc = acc & ExfLenKey(own(k))
            Next k
            acc = acc & "|"
            levelKey(i) = acc
        Next i
        g = ExfMapGet(groupIndex, acc)
        If g < 0 Then
            g = grpCount
            ExfMapSet groupIndex, acc, g
            For i = 0 To levels - 1
                grpKeys(i, g) = levelKey(i)
            Next i
            For k = 0 To p.keyCount - 1
                grpVals(k, g) = own(k)
            Next k
            grpFirst(g) = n
            grpCount = g + 1
        Else
            rowNext(grpLast(g)) = n
        End If
        grpLast(g) = n
        rowNext(n) = -1
        rowGrp(n) = g
    Next n

    ' --- Rows of several types (plan TYPEORDER): each group's rows by the rank
    ' of their _type in the source's order of types, a value it doesn't name
    ' last, each rank in the sheet's order - a stable counting sort of every
    ' row, dealt back to the groups.
    If p.typeOrderCount > 0 Then
        ExfMapInit rankIndex, p.typeOrderCount
        For k = 0 To p.typeOrderCount - 1
            ExfMapSet rankIndex, p.strs(p.typeOrder(k)), k
        Next k
        ReDim rowRank(0 To gRowCount)
        ReDim rankStart(0 To p.typeOrderCount)
        For n = 0 To gRowCount - 1
            If typeU >= 0 Then v = ExfTrim(gVals(typeU, n), gIsSpace) Else v = vbNullString
            k = ExfMapGet(rankIndex, v)
            If k < 0 Then k = p.typeOrderCount
            rowRank(n) = k
            rankStart(k) = rankStart(k) + 1
        Next n
        total = 0
        For k = 0 To p.typeOrderCount
            cnt = rankStart(k)
            rankStart(k) = total
            total = total + cnt
        Next k
        ReDim sortedRows(0 To gRowCount)
        For n = 0 To gRowCount - 1
            sortedRows(rankStart(rowRank(n))) = n
            rankStart(rowRank(n)) = rankStart(rowRank(n)) + 1
        Next n
        For g = 0 To grpCount - 1
            grpFirst(g) = -1
        Next g
        For i = 0 To gRowCount - 1
            n = sortedRows(i)
            g = rowGrp(n)
            If grpFirst(g) < 0 Then grpFirst(g) = n Else rowNext(grpLast(g)) = n
            grpLast(g) = n
            rowNext(n) = -1
        Next i
    End If

    ' --- Order of each row's fields: with sourceOrder, the known columns in
    ' the COL table's order - the source's - then the others in the sheet's
    ' order. Otherwise the sheet's order.
    ReDim writeU(0 To gUniqCount)
    If p.sourceOrder Then
        ReDim byCol(0 To p.colCount)
        For k = 0 To p.colCount - 1
            byCol(k) = -1
        Next k
        For u = 0 To gUniqCount - 1
            If gUniqKind(u) = EXF_KIND_COL Then byCol(gUniqColumn(u)) = u
        Next u
        ' A renamed attribute at its source column's place, which the sheet
        ' no longer has (macro 3.3).
        For u = 0 To gUniqCount - 1
            If gUniqKind(u) = EXF_KIND_RATTR Then byCol(gUniqRenamed(u)) = u
        Next u
        w = 0
        For k = 0 To p.colCount - 1
            If byCol(k) >= 0 Then
                writeU(w) = byCol(k)
                w = w + 1
            End If
        Next k
        For u = 0 To gUniqCount - 1
            If gUniqKind(u) <> EXF_KIND_COL And gUniqKind(u) <> EXF_KIND_RATTR Then
                writeU(w) = u
                w = w + 1
            End If
        Next u
    Else
        For u = 0 To gUniqCount - 1
            writeU(u) = u
        Next u
    End If

    ' --- Lookups
    ReDim isSelf(0 To p.strCount)
    For i = 0 To p.selfCloseCount - 1
        isSelf(p.selfClosing(i)) = True
    Next i
    ExfMapInit instanceIndex, p.instCount
    For t = 0 To p.instCount - 1
        acc = p.instLevel(t) & "#" & p.strs(p.instKey(t))
        If ExfMapGet(instanceIndex, acc) < 0 Then ExfMapSet instanceIndex, acc, t
    Next t
    ReDim isTypeCol(0 To gUniqCount)
    For u = 0 To gUniqCount - 1
        isTypeCol(u) = (gUniqName(u) = "_type")
    Next u

    ExfTreeInit p, gRowCount
    ReDim uniqNameId(0 To gUniqCount)
    For u = 0 To gUniqCount - 1
        uniqNameId(u) = -1
        If gUniqKind(u) = EXF_KIND_NEW Then uniqNameId(u) = ExfTreeNameIdOf(p, gUniqName(u))
        If gUniqKind(u) = EXF_KIND_RATTR Then uniqNameId(u) = ExfTreeNameIdOf(p, gUniqAttr(u))
    Next u

    ' Wrapper attributes in signature order (execute.ts attrSignature sorts the
    ' names): keyOrder lists, level by level, the KEY entries sorted by name.
    ReDim keyOrder(0 To p.keyCount)
    ReDim keyLen(0 To p.keyCount)
    For k = 0 To p.keyCount - 1
        keyLen(k) = ExfLenKey(p.strs(p.keyAttr(k)))
    Next k
    For i = 0 To levels - 1
        For j = 0 To p.wrapKeyCount(i) - 1
            k = j
            Do While k > 0
                If ExfCompareUnits(p.strs(p.keyAttr(keyOrder(p.wrapKeyStart(i) + k - 1))), _
                                   p.strs(p.keyAttr(p.wrapKeyStart(i) + j))) <= 0 Then Exit Do
                keyOrder(p.wrapKeyStart(i) + k) = keyOrder(p.wrapKeyStart(i) + k - 1)
                k = k - 1
            Loop
            keyOrder(p.wrapKeyStart(i) + k) = p.wrapKeyStart(i) + j
        Next j
    Next i

    ExfBuildRepairTables p

    ' --- Build
    root = ExfTreeNewNode(p.rootName, False, -1)
    ExfTreeSetRoot root
    For i = 0 To p.rootAttrCount - 1
        ExfTreeSetAttr root, p.rootAttrs(2 * i), p.strs(p.rootAttrs(2 * i + 1))
    Next i
    ' Siblings that came after the rows (reconstruct.ts layOutAround): laid out
    ' once every row is in. aftKind: 0 = rootList, 1 = wrapLists, 2 = instLists.
    ReDim aftParent(0 To grpCount + 1)
    ReDim aftKind(0 To grpCount + 1)
    ReDim aftStart(0 To grpCount + 1)
    ReDim aftCount(0 To grpCount + 1)
    ExfBuildLayOutAround p, root, 0, 0, p.rootListCount, p.rootRowsAt, 0, _
                         aftParent, aftKind, aftStart, aftCount, aftTotal

    ReDim newColumn(0 To gUniqCount)
    ReDim attrWritten(0 To gUniqCount)
    For g = 0 To grpCount - 1
        cursor = root
        For i = 0 To levels - 1
            If p.wrapOptional(i) = 1 Then
                ' Some container of this level lacked an attribute: the rows go
                ' back to their own one, by the values it was keyed with
                ' (ExfTreeOptionalKey for a slot).
                sig = "o|"
                For k = p.wrapKeyStart(i) To p.wrapKeyStart(i) + p.wrapKeyCount(i) - 1
                    If p.keyColumn(k) >= 0 Then sig = sig & ExfLenKey(grpVals(k, g))
                Next k
            Else
                sig = vbNullString
                For j = p.wrapKeyStart(i) To p.wrapKeyStart(i) + p.wrapKeyCount(i) - 1
                    sig = sig & keyLen(keyOrder(j)) & ExfLenKey(grpVals(keyOrder(j), g))
                Next j
            End If
            acc = cursor & "|" & p.strs(p.wrapName(i)) & "|" & sig
            wrapper = ExfTreeWrapperGet(acc)
            If wrapper < 0 Then
                wrapper = ExfTreeNewNode(p.wrapName(i), p.wrapSelfClosing(i) = 1, -1)
                For k = p.wrapKeyStart(i) To p.wrapKeyStart(i) + p.wrapKeyCount(i) - 1
                    ' An attribute some container lacked: not written empty on a new one.
                    If p.keyOptional(k) = 0 Or Len(grpVals(k, g)) > 0 Then ExfTreeSetAttr wrapper, p.keyAttr(k), grpVals(k, g)
                Next k
                ExfTreeAppend cursor, wrapper
                ExfTreeWrapperSet acc, wrapper
            End If
            ' First visit of this wrapper instance: its siblings, around the rows.
            If Not ExfTreeFilled(wrapper) Then
                ExfTreeMarkFilled wrapper
                t = ExfMapGet(instanceIndex, i & "#" & grpKeys(i, g))
                If t >= 0 Then
                    ExfBuildLayOutAround p, wrapper, 2, p.instListStart(t), p.instListCount(t), p.instRowsAt(t), i + 1, _
                                         aftParent, aftKind, aftStart, aftCount, aftTotal
                Else
                    ExfBuildLayOutAround p, wrapper, 1, p.wrapListStart(i), p.wrapListCount(i), p.wrapRowsAt(i), i + 1, _
                                         aftParent, aftKind, aftStart, aftCount, aftTotal
                End If
            End If
            cursor = wrapper
        Next i

        n = grpFirst(g)
        Do While n >= 0
            tagId = p.rowTag
            rowType = -1
            If p.isMultiTag Then
                If typeU < 0 Then
                    ExfSetError "errTypeColumnMissing", "values", typeList
                    Exit Function
                End If
                v = ExfTrim(gVals(typeU, n), gIsSpace)
                For t = 0 To p.typeCount - 1
                    If knownTypes(t) = v Then
                        rowType = t
                        Exit For
                    End If
                Next t
                If rowType < 0 Then
                    ExfSetError "errTypeEmpty", "row", CStr(gSheetRow(n)), "value", v, "values", typeList
                    Exit Function
                End If
                tagId = p.types(rowType)
            End If
            rowNode = ExfTreeNewNode(tagId, isSelf(tagId), -1)
            scoped = False
            If rowType >= 0 Then scoped = (p.typeScoped(rowType) = 1)
            stamp = n + 1
            ' Empty cells written attr="" (several row types without the list
            ' of each type's columns: none).
            If p.eaCount > 0 Then
                If Not p.isMultiTag Or scoped Then ExfBuildMarkEmpty p, n, stamp, scoped, rowType, allowed
            End If

            For w = 0 To gUniqCount - 1
                u = writeU(w)
                If Not isTypeCol(u) Then
                    ' (VBA evaluates both sides of And: no allowed(-1, u) when not scoped)
                    ' Left out: listed by ExfBuildFindCells (askCellsIgnored).
                    outOfType = False
                    If scoped Then outOfType = Not allowed(rowType, u)
                    If Not outOfType Then
                        If Len(gVals(u, n)) > 0 Then
                            If gUniqKind(u) = EXF_KIND_NEW Then
                                leaf = ExfTreeNewNode(uniqNameId(u), False, -1)
                                ExfTreeSetText leaf, gVals(u, n)
                                ExfTreeAppend rowNode, leaf
                                newColumn(u) = True
                            ElseIf gUniqKind(u) = EXF_KIND_COL Then
                                ExfTreeApplyColumn p, isSelf, rowNode, gUniqColumn(u), gVals(u, n), -1
                            ElseIf gUniqKind(u) = EXF_KIND_RATTR Then
                                ' A renamed attribute: its source's, under the new name.
                                ExfTreeApplyColumn p, isSelf, rowNode, gUniqRenamed(u), gVals(u, n), uniqNameId(u)
                                attrWritten(u) = True
                            End If
                        ElseIf mEaWrite(u) = stamp Then
                            ' An empty attribute the source always wrote: attr="".
                            If gUniqKind(u) = EXF_KIND_COL Then ExfTreeApplyColumn p, isSelf, rowNode, gUniqColumn(u), vbNullString, -1
                        End If
                    End If
                End If
            Next w
            ' Emptied values and occurrences left out.
            If p.trCount > 0 Or p.compact Then ExfBuildTidyRow p, rowNode, n, stamp
            ExfTreeAppend cursor, rowNode
            n = rowNext(n)
        Loop
    Next g

    For k = 0 To aftTotal - 1
        Select Case aftKind(k)
            Case 0
                ExfTreeLayOut p, aftParent(k), p.rootList, aftStart(k), aftCount(k), -1
            Case 1
                ExfTreeLayOut p, aftParent(k), p.wrapLists, aftStart(k), aftCount(k), -1
            Case Else
                ExfTreeLayOut p, aftParent(k), p.instLists, aftStart(k), aftCount(k), -1
        End Select
    Next k

    ExfTreePruneSlots
    For u = 0 To gUniqCount - 1
        If newColumn(u) Then
            If Len(gNewColumns) > 0 Then gNewColumns = gNewColumns & ","
            gNewColumns = gNewColumns & gUniqName(u)
        End If
        ' Left out after Yes (successIgnoredColumns): not a copy, nor a renamed
        ' header written under its new name.
        If mLeftOut(u) Or (mRenamedHit(u) And Not newColumn(u) And Not attrWritten(u)) Then
            If Len(gIgnoredColumns) > 0 Then gIgnoredColumns = gIgnoredColumns & ","
            gIgnoredColumns = gIgnoredColumns & gUniqName(u)
        End If
    Next u
    Erase gVals        ' the tree holds its own copy: memory back before writing
    Erase mColEaStart, mColEaCount, mColTrStart, mColTrCount, mEaU, mTrU, mEaHeld, mTrHeld, mEaWrite, mEaThrough, mTrThrough
    Erase mLeftOut, mRenamedHit
    ExfEngineBuild = True
End Function

' = execute.ts rowRepairsOf: the value repairs' tables by COL entry and by
' unique column (EAUNDER and TRUNDER come sorted by COL entry).
Private Sub ExfBuildRepairTables(ByRef p As ExfPlan)
    Dim i As Long, k As Long, e As Long, u As Long, eaElements As Long, trElements As Long
    ReDim mColEaStart(0 To p.colCount)
    ReDim mColEaCount(0 To p.colCount)
    ReDim mColTrStart(0 To p.colCount)
    ReDim mColTrCount(0 To p.colCount)
    For i = 0 To p.eaUnderCount - 1
        k = p.eaUnderCol(i)
        If mColEaCount(k) = 0 Then mColEaStart(k) = i
        mColEaCount(k) = mColEaCount(k) + 1
        If p.eaUnderElement(i) >= eaElements Then eaElements = p.eaUnderElement(i) + 1
    Next i
    For i = 0 To p.trUnderCount - 1
        k = p.trUnderCol(i)
        If mColTrCount(k) = 0 Then mColTrStart(k) = i
        mColTrCount(k) = mColTrCount(k) + 1
        If p.trUnderElement(i) >= trElements Then trElements = p.trUnderElement(i) + 1
    Next i
    ReDim mEaU(0 To p.eaCount)
    For e = 0 To p.eaCount - 1
        mEaU(e) = ExfMapGet(gUniqIndex, p.strs(p.colName(p.eaCol(e))))
        If p.eaElement(e) >= eaElements Then eaElements = p.eaElement(e) + 1
    Next e
    ReDim mTrU(0 To p.trCount)
    For e = 0 To p.trCount - 1
        mTrU(e) = ExfMapGet(gUniqIndex, p.strs(p.colName(p.trCol(e))))
        If p.trElement(e) >= trElements Then trElements = p.trElement(e) + 1
    Next e
    ReDim mEaHeld(0 To eaElements)
    ReDim mTrHeld(0 To trElements)
    ReDim mEaWrite(0 To gUniqCount)
    ' The only columns a row is looked at for (a wide sheet has thousands of others).
    ReDim mEaThrough(0 To gUniqCount)
    ReDim mTrThrough(0 To gUniqCount)
    mEaThroughCount = 0
    mTrThroughCount = 0
    For u = 0 To gUniqCount - 1
        k = gUniqSchema(u)
        If k >= 0 Then
            If mColEaCount(k) > 0 Then
                mEaThrough(mEaThroughCount) = u
                mEaThroughCount = mEaThroughCount + 1
            End If
            If mColTrCount(k) > 0 Then
                mTrThrough(mTrThroughCount) = u
                mTrThroughCount = mTrThroughCount + 1
            End If
        End If
    Next u
End Sub

' = execute.ts (row loop; value-repairs.ts RowRepairs.emptyCellsToWrite): the
' empty cells of row n written attr="" - the column in the sheet and allowed
' for the row's type, its element written anyway: a filled cell of the row,
' allowed too, goes through it (the row element always is).
Private Sub ExfBuildMarkEmpty(ByRef p As ExfPlan, ByVal n As Long, ByVal stamp As Long, ByVal scoped As Boolean, _
                              ByVal rowType As Long, ByRef allowed() As Boolean)
    Dim i As Long, u As Long, k As Long, j As Long, e As Long, ok As Boolean
    For i = 0 To mEaThroughCount - 1
        u = mEaThrough(i)
        If Len(gVals(u, n)) > 0 Then
            k = gUniqSchema(u)
            ok = True
            If scoped Then ok = allowed(rowType, u)
            If ok Then
                For j = mColEaStart(k) To mColEaStart(k) + mColEaCount(k) - 1
                    mEaHeld(p.eaUnderElement(j)) = stamp
                Next j
            End If
        End If
    Next i
    For e = 0 To p.eaCount - 1
        u = mEaU(e)
        If u >= 0 Then
            If Len(gVals(u, n)) = 0 Then
                ok = True
                If scoped Then ok = allowed(rowType, u)
                If ok Then
                    If p.eaElement(e) < 0 Then
                        mEaWrite(u) = stamp
                    ElseIf mEaHeld(p.eaElement(e)) = stamp Then
                        mEaWrite(u) = stamp
                    End If
                End If
            End If
        End If
    Next e
End Sub

' = execute.ts tidyRow (value-repairs.ts RowRepairs.tidy): once the row is
' built, an element whose value the source always had, emptied while its
' column is in the sheet, goes with its attributes - found first, removed
' after; then, with numbered columns or after such a removal, the elements
' left with nothing in them (ExfTreePrune). Only an element some cell of the
' row goes through is looked at: a filled cell, or one the clean-up left empty.
Private Sub ExfBuildTidyRow(ByRef p As ExfPlan, ByVal rowNode As Long, ByVal n As Long, ByVal stamp As Long)
    Dim i As Long, u As Long, k As Long, j As Long, t As Long, el As Long, hit As Boolean, removed As Boolean
    Dim found() As Long, foundCount As Long
    If p.trCount > 0 Then
        For i = 0 To mTrThroughCount - 1
            u = mTrThrough(i)
            k = gUniqSchema(u)
            hit = (Len(gVals(u, n)) > 0)
            If Not hit And mAnyCleaned Then hit = (ExfMapGet(mCleaned, n & ":" & u) >= 0)
            If hit Then
                For j = mColTrStart(k) To mColTrStart(k) + mColTrCount(k) - 1
                    mTrHeld(p.trUnderElement(j)) = stamp
                Next j
            End If
        Next i
        ReDim found(0 To p.trCount)
        For t = 0 To p.trCount - 1
            If mTrHeld(p.trElement(t)) = stamp Then
                u = mTrU(t)
                If u >= 0 Then
                    If Len(gVals(u, n)) = 0 Then
                        el = ExfTreeFindAt(p, rowNode, p.trCol(t))
                        If el >= 0 Then
                            If ExfTreeIsBare(el) Then
                                found(foundCount) = el
                                foundCount = foundCount + 1
                            End If
                        End If
                    End If
                End If
            End If
        Next t
        For j = 0 To foundCount - 1
            ExfTreeRemove found(j)
            removed = True
        Next j
    End If
    If p.compact Or removed Then ExfTreePrune p, rowNode, vbNullString, 0
End Sub

' The siblings before the rows now, the others recorded for after them
' (rowsAt -1: all before). Port of layOutAround in
' src/lib/excel-macro/engine/execute.ts; level: the wrapper level whose rows
' look among the parent's children.
Private Sub ExfBuildLayOutAround(ByRef p As ExfPlan, ByVal parentNode As Long, ByVal kind As Long, _
                                 ByVal start As Long, ByVal count As Long, ByVal rowsAt As Long, ByVal level As Long, _
                                 ByRef aftParent() As Long, ByRef aftKind() As Long, ByRef aftStart() As Long, _
                                 ByRef aftCount() As Long, ByRef aftTotal As Long)
    Dim before As Long
    before = count
    If rowsAt >= 0 And rowsAt <= count Then before = rowsAt
    Select Case kind
        Case 0
            ExfTreeLayOut p, parentNode, p.rootList, start, before, level
        Case 1
            ExfTreeLayOut p, parentNode, p.wrapLists, start, before, level
        Case Else
            ExfTreeLayOut p, parentNode, p.instLists, start, before, level
    End Select
    If before < count Then
        aftParent(aftTotal) = parentNode
        aftKind(aftTotal) = kind
        aftStart(aftTotal) = start + before
        aftCount(aftTotal) = count - before
        aftTotal = aftTotal + 1
    End If
End Sub

' = execute.ts leftOutAs (reconstruct.ts leftOutAs): 0 written, 1 added (a
' column the source didn't have, in a sheet with a _type column), 2 a row type
' without such a field. A wrapper attribute's column is always written.
Private Function ExfBuildLeftOut(ByRef p As ExfPlan, ByVal u As Long, ByVal n As Long, ByRef rowTypeOf() As Long, ByRef allowed() As Boolean) As Long
    Dim t As Long
    If gUniqAncestor(u) Then Exit Function
    If p.isMultiTag Then
        t = rowTypeOf(n)
        If t < 0 Then Exit Function
        If p.typeScoped(t) = 1 Then
            If Not allowed(t, u) Then
                If gUniqKind(u) = EXF_KIND_COL Then ExfBuildLeftOut = 2 Else ExfBuildLeftOut = 1
                Exit Function
            End If
        End If
    End If
    If gUniqKind(u) = EXF_KIND_BAD Then ExfBuildLeftOut = 1
End Function

' = execute.ts findCells: the filled cells the rebuild leaves out (on the raw
' values, column by column), a renamed header (said as such, whether or not
' its cells are written), the copies of a name whose values differ - unless
' that column is an added one, left out anyway -, in the order of the sheet;
' then the characters XML forbids, row by row, cleaned in place (the cells of
' _type aside), reported where the cell is written. Builds the lists of the
' two questions (report.ts askIgnoredList, askInvalidList).
Private Sub ExfBuildFindCells(ByRef p As ExfPlan, ByRef rowTypeOf() As Long, ByRef allowed() As Boolean, _
                              ByRef knownTypes() As String, ByVal typeU As Long)
    Dim u As Long, n As Long, i As Long, k As Long, why As Long, firstWhy As Long, cnt As Long
    Dim blank As Boolean, rows3() As Long, typeNames As String, lineCount As Long, lst As String
    Dim typeSeen() As Boolean, typeShown As Long, t As Long
    Dim removed() As Long, removedCount As Long, unitName As String
    Dim invCnt() As Long, invRows() As Long, invCodes() As String, invCodeCount() As Long
    Dim invOrder() As Long, invTotal As Long, renamedLines As Long

    ReDim rows3(0 To 2)
    ReDim mLeftOut(0 To gUniqCount)
    ReDim mRenamedHit(0 To gUniqCount)
    For u = 0 To gUniqCount - 1
        ' A renamed header (reconstruct.ts ignoredColumns): never blank, never
        ' in several columns; _type and _order aside.
        If gUniqRenamed(u) >= 0 And gUniqName(u) <> "_type" And gUniqName(u) <> "_order" Then
            cnt = 0
            For n = 0 To gRowCount - 1
                If Len(gVals(u, n)) > 0 Then
                    If cnt < 3 Then rows3(cnt) = gSheetRow(n)
                    cnt = cnt + 1
                End If
            Next n
            If cnt > 0 Then
                mRenamedHit(u) = True
                If lineCount < 3 Then
                    ExfBuildAddLine lst, ExfFill(ExfMessageText("listRenamed"), "column", ExfBuildAskName(gUniqName(u)), _
                        "cells", ExfBuildAskCells(ExfEngineLetter(u), rows3, cnt), "source", ExfBuildAskName(p.strs(p.colName(gUniqRenamed(u)))))
                End If
                lineCount = lineCount + 1
                renamedLines = renamedLines + 1
            End If
        End If
        blank = (Len(ExfTrim(gUniqName(u), gIsSpace)) = 0)
        firstWhy = 0
        cnt = 0
        ' The row types named on the line (report.ts typeList): the first 2,
        ' then ", ...".
        typeNames = vbNullString
        typeShown = 0
        ReDim typeSeen(0 To p.typeCount)
        ' Outside a sheet with a _type column only an invalid name leaves cells
        ' out - and it stopped the macro already (ExfEngineCheckColumns).
        If Not blank And u <> typeU And Not gUniqAncestor(u) And (p.isMultiTag Or gUniqKind(u) = EXF_KIND_BAD) And gUniqRenamed(u) < 0 Then
            For n = 0 To gRowCount - 1
                If Len(gVals(u, n)) > 0 Then
                    why = ExfBuildLeftOut(p, u, n, rowTypeOf, allowed)
                    If why > 0 Then
                        If firstWhy = 0 Then firstWhy = why
                        If cnt < 3 Then rows3(cnt) = gSheetRow(n)
                        cnt = cnt + 1
                        t = rowTypeOf(n)
                        If why = 2 Then
                            If Not typeSeen(t) Then
                                typeSeen(t) = True
                                If typeShown < 2 Then
                                    If typeShown > 0 Then typeNames = typeNames & ", "
                                    typeNames = typeNames & ExfBuildAskName(knownTypes(t))
                                ElseIf typeShown = 2 Then
                                    typeNames = typeNames & ", " & ChrW(8230)
                                End If
                                typeShown = typeShown + 1
                            End If
                        End If
                    End If
                End If
            Next n
        End If
        If firstWhy > 0 Then
            mLeftOut(u) = True
            If lineCount < 3 Then
                If firstWhy = 2 Then
                    ExfBuildAddLine lst, ExfFill(ExfMessageText("listOtherType"), "column", ExfBuildAskName(gUniqName(u)), _
                        "cells", ExfBuildAskCells(ExfEngineLetter(u), rows3, cnt), "types", typeNames)
                Else
                    ExfBuildAddLine lst, ExfFill(ExfMessageText("listAdded"), "column", ExfBuildAskName(gUniqName(u)), _
                        "cells", ExfBuildAskCells(ExfEngineLetter(u), rows3, cnt))
                End If
            End If
            lineCount = lineCount + 1
        End If
        If gDupCount(u) > 0 And Not blank And firstWhy <> 1 Then
            If lineCount < 3 Then
                For i = 0 To 2
                    rows3(i) = gDupRows(u, i)
                Next i
                ExfBuildAddLine lst, ExfFill(ExfMessageText("listDuplicate"), "column", ExfBuildAskName(gUniqName(u)), _
                    "cells", ExfBuildAskCells(ExfEngineLetter(u), rows3, gDupCount(u)), _
                    "letters", ExfEngineLetters(u), "first", ExfEngineLetter(u))
            End If
            lineCount = lineCount + 1
        End If
    Next u
    If lineCount > 3 Then lst = lst & vbLf & ExfFill(ExfMessageText("listMoreLines"), "count", CStr(lineCount))
    gAskIgnored = lst
    If lineCount > 0 And renamedLines = lineCount Then gAskIgnoredKey = "askRenamed" Else gAskIgnoredKey = "askCellsIgnored"

    ' Characters XML forbids: entries in the order they are first met. A cell
    ' the clean-up leaves empty is noted (ExfBuildTidyRow).
    ExfMapInit mCleaned, 16
    mAnyCleaned = False
    If Not gAnyDirty Then Exit Sub
    ReDim removed(0 To 7)
    ReDim invCnt(0 To gUniqCount)
    ReDim invRows(0 To gUniqCount, 0 To 2)
    ReDim invCodes(0 To gUniqCount)
    ReDim invCodeCount(0 To gUniqCount)
    ReDim invOrder(0 To gUniqCount)
    For n = 0 To gRowCount - 1
        If gRowDirty(n) Then
            For u = 0 To gUniqCount - 1
                If u <> typeU Then
                    If ExfMayHoldInvalid(gVals(u, n)) Then
                        removedCount = 0
                        gVals(u, n) = ExfCleanInvalid(gVals(u, n), removed, removedCount)
                        If Len(gVals(u, n)) = 0 Then
                            ExfMapSet mCleaned, n & ":" & u, 1
                            mAnyCleaned = True
                        End If
                        If removedCount > 0 Then
                            If Len(ExfTrim(gUniqName(u), gIsSpace)) > 0 Then
                                If ExfBuildLeftOut(p, u, n, rowTypeOf, allowed) = 0 Then
                                    If invCnt(u) = 0 Then
                                        invOrder(invTotal) = u
                                        invTotal = invTotal + 1
                                    End If
                                    If invCnt(u) < 3 Then invRows(u, invCnt(u)) = gSheetRow(n)
                                    invCnt(u) = invCnt(u) + 1
                                    For i = 0 To removedCount - 1
                                        unitName = ExfUnitCode(removed(i))
                                        If invCodeCount(u) < 8 Then
                                            If InStr(1, ", " & invCodes(u) & ",", ", " & unitName & ",", vbBinaryCompare) = 0 Then
                                                If invCodeCount(u) > 0 Then invCodes(u) = invCodes(u) & ", "
                                                invCodes(u) = invCodes(u) & unitName
                                                invCodeCount(u) = invCodeCount(u) + 1
                                            End If
                                        End If
                                    Next i
                                End If
                            End If
                        End If
                    End If
                End If
            Next u
        End If
    Next n
    lst = vbNullString
    For k = 0 To invTotal - 1
        If k = 3 Then
            lst = lst & vbLf & ExfFill(ExfMessageText("listMoreLines"), "count", CStr(invTotal))
            Exit For
        End If
        u = invOrder(k)
        For i = 0 To 2
            rows3(i) = invRows(u, i)
        Next i
        ExfBuildAddLine lst, ExfFill(ExfMessageText("listInvalid"), "column", ExfBuildAskName(gUniqName(u)), _
            "cells", ExfBuildAskCells(ExfEngineLetter(u), rows3, invCnt(u)), "codes", invCodes(u))
    Next k
    gAskInvalid = lst
End Sub

' One more line of a question's list.
Private Sub ExfBuildAddLine(ByRef lst As String, ByVal lineText As String)
    If Len(lst) > 0 Then lst = lst & vbLf
    lst = lst & lineText
End Sub

' = report.ts shortName: a column or type name cut at 32 characters.
Public Function ExfBuildAskName(ByVal nm As String) As String
    If Len(nm) > 32 Then ExfBuildAskName = Left$(nm, 32) & ChrW(8230) Else ExfBuildAskName = nm
End Function

' = report.ts cellList: "F7, F12, F20", then "F7, F12, F20..., 9 in all"
' (listMoreCells, with the total).
Public Function ExfBuildAskCells(ByVal letter As String, ByRef rows3() As Long, ByVal cnt As Long) As String
    Dim i As Long, shown As Long, s As String
    shown = cnt
    If shown > 3 Then shown = 3
    For i = 0 To shown - 1
        If i > 0 Then s = s & ", "
        s = s & letter & CStr(rows3(i))
    Next i
    If cnt > shown Then s = ExfFill(ExfMessageText("listMoreCells"), "cells", s, "count", CStr(cnt))
    ExfBuildAskCells = s
End Function
modExfData.basReading the "Data" sheet253 lines
Attribute VB_Name = "modExfData"
' ExcelifyXML - reads the Data sheet: row 1 = the technical names, row 2 = your
' labels (never read), data below. Cells are read by blocks of 500 rows (32-bit
' Excel has 2 GB of memory for everything). Every cell is formatted as Text, so
' values are normally text as typed; a number, date or TRUE/FALSE pasted with
' its format is turned into text by fixed rules and reported at the end.
' Reference: sliceDataSheet in src/lib/excel-macro/engine/execute.ts.
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary
Option Private Module

Private Const CHUNK_ROWS As Long = 500
Private Const LABEL_STYLE As String = "ExcelifyLabel"     ' prefix of the 3 label styles
Private Const LABELS_NAME As String = "ExcelifyLabels"    ' defined name of row 2

Public Type ExfSheet
    lastRow As Long
    nCols As Long
    headers() As String          ' row 1, 0 To nCols - 1
    labelsRow As Long            ' row of the labels, 0 when deleted
    firstRow As Long             ' first data row
    conversions As Long          ' cells that were not text
    convCells(0 To 4) As String  ' the first five of them
End Type

' Row 1, and where the data starts. False when a message must be shown.
Public Function ExfReadHeaders(ByVal ws As Worksheet, ByRef sh As ExfSheet) As Boolean
    Dim block As Variant, v As Variant, c As Long, hasHeader As Boolean, nameRow As Long

    sh.lastRow = ExfLastCell(ws, xlByRows)
    sh.nCols = ExfLastCell(ws, xlByColumns)
    If sh.nCols = 0 Then
        ExfSetError "errNoHeaders", "sheet", ws.Name
        Exit Function
    End If
    block = ExfBlock(ws, 1, 1, sh.nCols)
    ReDim sh.headers(0 To sh.nCols - 1)
    For c = 1 To sh.nCols
        v = block(1, c)
        If VarType(v) = vbString Then
            sh.headers(c - 1) = v
        ElseIf IsEmpty(v) Then
            sh.headers(c - 1) = vbNullString
        ElseIf IsError(v) Then
            ExfSetError "errCellError", "cell", ws.Cells(1, c).Address(False, False), "value", ExfErrorText(ws, 1, c, v)
            Exit Function
        Else
            sh.headers(c - 1) = ExfConvert(ws, 1, c, v)
        End If
        If Len(sh.headers(c - 1)) > 0 Then hasHeader = True
    Next c
    If Not hasHeader Then
        ExfSetError "errNoHeaders", "sheet", ws.Name
        Exit Function
    End If

    ' The labels row is found by its defined name (follows inserted and deleted
    ' rows) and by its style (moves with the cells when a sort takes it along).
    nameRow = ExfNamedRow(ws)
    If nameRow > 0 Then
        If ExfIsLabelsRow(ws, nameRow) Then sh.labelsRow = nameRow
    End If
    If sh.labelsRow = 0 Then
        sh.labelsRow = ExfFindLabelsRow(ws, sh.lastRow)
        ' Styles cleared but the name still in place: it is still the labels row.
        If sh.labelsRow = 0 Then sh.labelsRow = nameRow
    End If
    If sh.labelsRow <> 0 And sh.labelsRow <> 2 Then
        ExfSetError "errLabelRowMoved", "row", CStr(sh.labelsRow), "sheet", ws.Name
        Exit Function
    End If
    If sh.labelsRow = 2 Then sh.firstRow = 3 Else sh.firstRow = 2
    ExfReadHeaders = True
End Function

' Every data row, in sheet order, handed to the engine (ExfEngineAddRow).
Public Function ExfReadRows(ByVal ws As Worksheet, ByRef sh As ExfSheet) As Boolean
    Dim block As Variant, v As Variant, rowCells() As String
    Dim r1 As Long, r2 As Long, r As Long, c As Long, total As Long, chunkNo As Long

    ExfReadRows = True
    If sh.firstRow > sh.lastRow Then Exit Function
    ReDim rowCells(0 To sh.nCols - 1)
    total = sh.lastRow - sh.firstRow + 1
    For r1 = sh.firstRow To sh.lastRow Step CHUNK_ROWS
        r2 = r1 + CHUNK_ROWS - 1
        If r2 > sh.lastRow Then r2 = sh.lastRow
        block = ExfBlock(ws, r1, r2 - r1 + 1, sh.nCols)
        For r = 1 To r2 - r1 + 1
            For c = 1 To sh.nCols
                v = block(r, c)
                If VarType(v) = vbString Then
                    rowCells(c - 1) = v
                ElseIf IsEmpty(v) Then
                    rowCells(c - 1) = vbNullString
                ElseIf IsError(v) Then
                    ExfSetError "errCellError", "cell", ws.Cells(r1 + r - 1, c).Address(False, False), _
                        "value", ExfErrorText(ws, r1 + r - 1, c, v)
                    ExfReadRows = False
                    Exit Function
                Else
                    rowCells(c - 1) = ExfConvert(ws, r1 + r - 1, c, v)
                    sh.conversions = sh.conversions + 1
                    If sh.conversions <= 5 Then
                        sh.convCells(sh.conversions - 1) = ws.Cells(r1 + r - 1, c).Address(False, False)
                    End If
                End If
            Next c
            ExfEngineAddRow rowCells, r1 + r - 1
        Next r
        chunkNo = chunkNo + 1
        If chunkNo Mod 20 = 0 Then
            ExfStatus ExfFill(ExfMessageText("progressReading"), "done", CStr(r2 - sh.firstRow + 1), "total", CStr(total))
            DoEvents
        End If
    Next r1
End Function

' A cell that is not text (typed or pasted with its format), as text:
' TRUE/FALSE -> true/false; dates -> YYYY-MM-DD, with THH:MM:SS when there is a
' time; whole numbers below 10^15 -> digits only; other numbers -> invariant
' notation with a decimal point (never the regional settings of Excel).
Private Function ExfConvert(ByVal ws As Worksheet, ByVal r As Long, ByVal c As Long, ByRef v As Variant) As String
    Dim d As Variant
    If VarType(v) = vbBoolean Then
        If v Then ExfConvert = "true" Else ExfConvert = "false"
        Exit Function
    End If
    ' Value2 gives dates as numbers; Value tells them apart.
    d = ws.Cells(r, c).Value
    If VarType(d) = vbDate Then
        ExfConvert = ExfIsoDate(CDate(d))
    Else
        ExfConvert = ExfNumberText(CDbl(v))
    End If
End Function

Private Function ExfIsoDate(ByVal d As Date) As String
    Dim days As Double, dayTime As Double
    days = Int(CDbl(d))
    dayTime = CDbl(d) - days
    If dayTime = 0 Then
        ExfIsoDate = Format$(d, "yyyy\-mm\-dd")
    ElseIf days = 0 Then
        ExfIsoDate = Format$(d, "hh\:nn\:ss")
    Else
        ExfIsoDate = Format$(d, "yyyy\-mm\-dd") & "T" & Format$(d, "hh\:nn\:ss")
    End If
End Function

Private Function ExfNumberText(ByVal x As Double) As String
    Dim s As String
    If x = Fix(x) And Abs(x) < 1E+15 Then
        ExfNumberText = Format$(x, "0")
        Exit Function
    End If
    ' Str$ is invariant (decimal point) but drops the leading zero: -.5, .5
    s = Trim$(Str$(x))
    If Left$(s, 1) = "." Then
        s = "0" & s
    ElseIf Left$(s, 2) = "-." Then
        s = "-0" & Mid$(s, 2)
    End If
    ExfNumberText = s
End Function

' What the cell shows (#N/A, #VALEUR!...), else the English name of the error.
Private Function ExfErrorText(ByVal ws As Worksheet, ByVal r As Long, ByVal c As Long, ByRef v As Variant) As String
    Dim s As String, codes As Variant, errNames As Variant, i As Long
    On Error Resume Next
    s = ws.Cells(r, c).Text
    On Error GoTo 0
    If Left$(s, 1) = "#" Then
        ExfErrorText = s
        Exit Function
    End If
    codes = Array(2000, 2007, 2015, 2023, 2029, 2036, 2042, 2043, 2045, 2046, 2047, 2048, 2049, 2050)
    errNames = Array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A", "#GETTING_DATA", _
        "#SPILL!", "#CONNECT!", "#BLOCKED!", "#UNKNOWN!", "#FIELD!", "#CALC!")
    For i = 0 To UBound(codes)
        If v = CVErr(codes(i)) Then
            ExfErrorText = errNames(i)
            Exit Function
        End If
    Next i
    ExfErrorText = "#?"
End Function

' Row of the defined name ExcelifyLabels on this sheet, 0 when it is missing
' or broken (#REF! once the row has been deleted).
Private Function ExfNamedRow(ByVal ws As Worksheet) As Long
    Dim rg As Range
    On Error Resume Next
    Set rg = ws.Parent.Names(LABELS_NAME).RefersToRange
    On Error GoTo 0
    If rg Is Nothing Then Exit Function
    If rg.Worksheet.CodeName <> ws.CodeName Then Exit Function
    ExfNamedRow = rg.Row
End Function

Private Function ExfIsLabelsRow(ByVal ws As Worksheet, ByVal r As Long) As Boolean
    Dim s As String
    On Error Resume Next
    s = ws.Cells(r, 1).Style.Name
    On Error GoTo 0
    ExfIsLabelsRow = (Left$(s, Len(LABEL_STYLE)) = LABEL_STYLE)
End Function

' First row whose first cell has a label style, 0 when there is none.
Private Function ExfFindLabelsRow(ByVal ws As Worksheet, ByVal lastRow As Long) As Long
    Dim r As Long
    For r = 1 To lastRow
        If ExfIsLabelsRow(ws, r) Then
            ExfFindLabelsRow = r
            Exit Function
        End If
    Next r
End Function

' Cells of a rectangle as a 1-based 2-D array, even for a single cell.
Public Function ExfBlock(ByVal ws As Worksheet, ByVal firstRow As Long, ByVal rows As Long, ByVal cols As Long) As Variant
    Dim v As Variant, one(1 To 1, 1 To 1) As Variant
    v = ws.Range(ws.Cells(firstRow, 1), ws.Cells(firstRow + rows - 1, cols)).Value2
    If IsArray(v) Then
        ExfBlock = v
    Else
        one(1, 1) = v
        ExfBlock = one
    End If
End Function

' Last used row (xlByRows) or column (xlByColumns), 0 on an empty sheet.
' LookIn:=xlFormulas also sees hidden and filtered cells, which are exported.
Public Function ExfLastCell(ByVal ws As Worksheet, ByVal order As XlSearchOrder) As Long
    Dim hit As Range
    Set hit = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:=xlPart, _
        SearchOrder:=order, SearchDirection:=xlPrevious)
    If hit Is Nothing Then Exit Function
    If order = xlByRows Then ExfLastCell = hit.Row Else ExfLastCell = hit.Column
End Function

' Sheets are found by their code name: the tabs may be renamed.
Public Function ExfSheetByCodeName(ByVal book As Workbook, ByVal wantedName As String) As Worksheet
    Dim ws As Worksheet
    For Each ws In book.Worksheets
        If ws.CodeName = wantedName Then
            Set ExfSheetByCodeName = ws
            Exit Function
        End If
    Next ws
End Function
modExfEngine.basRebuilding the XML (1/4): columns and rows of the "Data" sheet833 lines
Attribute VB_Name = "modExfEngine"
' ExcelifyXML - the reconstruction engine, part 1: the columns and rows of the
' Data sheet. A line-by-line port of executePlan in
' src/lib/excel-macro/engine/execute.ts, itself proven byte-identical to the
' website's online reconstruction: same tables, same order of operations,
' same output. Part 2 (modExfBuild) groups the rows and builds the element
' tree, part 3 (modExfTree) holds the tree, part 4 (modExfWrite) writes the
' XML.
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary
Option Private Module

Public Const EXF_KIND_SKIP As Long = 0  ' _type, _order, wrapper attribute columns
Public Const EXF_KIND_COL As Long = 1   ' known column
Public Const EXF_KIND_NEW As Long = 2   ' unknown column with a valid XML name: a new element
Public Const EXF_KIND_BAD As Long = 3   ' unknown column with an invalid name
Public Const EXF_KIND_RATTR As Long = 4 ' a renamed attribute's header: its source's attribute, new name (macro 3.3)

' Shared with modExfBuild. A name met in several columns is read from its
' leftmost one, the one the site writes; the other copies are compared with it.
Public gUniqCount As Long
Public gUniqName() As String
Public gUniqKind() As Long
Public gUniqColumn() As Long            ' entry of the COL table for a known column
Public gUniqSchema() As Long            ' entry of the COL table for any name, _type too (-1: none)
Public gUniqAncestor() As Boolean       ' a wrapper attribute's column: never left out
Public gUniqIndex As ExfStrMap
Public gRowCount As Long                ' rows kept (entirely empty rows skipped)
Public gVals() As String                ' values by (unique column, row)
Public gSheetRow() As Long              ' sheet row of each kept row, for messages
Public gRowDirty() As Boolean           ' kept rows that may hold a character XML forbids
Public gAnyDirty As Boolean
Public gDupCount() As Long              ' by unique name: rows where a copy differs
Public gDupRows() As Long               ' (unique name, 0 To 2): the first of those sheet rows
Public gIsSpace() As Boolean            ' code units String.prototype.trim removes
Public gNewColumns As String            ' results, comma-separated
Public gIgnoredColumns As String
Public gAskIgnored As String            ' the lists of the questions ("": no question)
Public gAskIgnoredKey As String         ' askCellsIgnored, or askRenamed when every line is a renamed header
Public gAskInvalid As String
Public gAskChanges As String            ' values changed that can't be put back (macro 3.1: every kind)
Public gAskChangesKey As String         ' askLeadingZeros, or askValuesChanged when another kind is listed
Public gPadded As String                ' codes given their leading zeros back: "column=cells,..."
Public gUniqRenamed() As Long           ' by unique name: the COL entry a renamed header stands in for, -1
Public gUniqAttr() As String            ' by unique name: a renamed attribute's new name (macro 3.3), "" none

Private mCols As Long                   ' sheet columns read
Private mHeaders() As String
Private mColUniq() As Long              ' unique name of each sheet column
Private mUniqCol() As Long              ' sheet column a unique name is read from: its leftmost
Private mBadCols() As Long              ' sheet columns whose name is invalid
Private mBadCount As Long
Private mBadData() As Boolean           ' ... and that hold data
Private mExtraCols() As Long            ' sheet columns that are not their name's leftmost
Private mExtraCount As Long
Private mDupLast() As Long              ' by unique name: the sheet row last counted
Private mHasUpper() As Boolean          ' the plan's CASE table, by code unit
Private mUpper() As String
Private mAliasU As ExfStrMap            ' a renamed header's source name -> the header's unique column
Private mBareAll As Boolean             ' every row of the sheet's type: not written when bare (BARETYPE)
Private mBareMulti As Boolean           ' rows of several types: looked up in mBareTypes
Private mBareTypes As ExfStrMap
Private mTypeCol As Long                ' sheet column of the leftmost _type, -1
Private mBareSkip() As Boolean          ' by unique name: _type, _order or a context column

' Row 1 read: which columns are known, new or invalid. False on _order.
Public Function ExfEngineStart(ByRef p As ExfPlan, ByRef headers() As String, ByVal nCols As Long) As Boolean
    Dim c As Long, u As Long, k As Long, nm As String
    Dim colIndex As ExfStrMap, ancestorIndex As ExfStrMap

    ExfEngineReset
    mCols = nCols
    ReDim mHeaders(0 To nCols - 1)
    ReDim mColUniq(0 To nCols - 1)
    ReDim gUniqName(0 To nCols - 1)
    ReDim mUniqCol(0 To nCols - 1)
    ReDim mBadData(0 To nCols - 1)
    ReDim mBadCols(0 To nCols - 1)
    ReDim mExtraCols(0 To nCols - 1)
    ExfMapInit gUniqIndex, nCols
    For c = 0 To nCols - 1
        mHeaders(c) = headers(c)
        u = ExfMapGet(gUniqIndex, headers(c))
        If u < 0 Then
            u = gUniqCount
            ExfMapSet gUniqIndex, headers(c), u
            gUniqName(u) = headers(c)
            gUniqCount = u + 1
            mUniqCol(u) = c
        Else
            mExtraCols(mExtraCount) = c
            mExtraCount = mExtraCount + 1
        End If
        mColUniq(c) = u
    Next c

    ExfMapInit colIndex, p.colCount
    For k = 0 To p.colCount - 1
        If ExfMapGet(colIndex, p.strs(p.colName(k))) < 0 Then ExfMapSet colIndex, p.strs(p.colName(k)), k
    Next k
    ExfMapInit ancestorIndex, p.ancestorCount
    For k = 0 To p.ancestorCount - 1
        ExfMapSet ancestorIndex, p.strs(p.ancestorCols(k)), k
    Next k

    ReDim gUniqKind(0 To gUniqCount - 1)
    ReDim gUniqColumn(0 To gUniqCount - 1)
    ReDim gUniqSchema(0 To gUniqCount - 1)
    ReDim gUniqAncestor(0 To gUniqCount - 1)
    ReDim gDupCount(0 To gUniqCount - 1)
    ReDim gDupRows(0 To gUniqCount - 1, 0 To 2)
    ReDim mDupLast(0 To gUniqCount - 1)
    For u = 0 To gUniqCount - 1
        nm = gUniqName(u)
        mDupLast(u) = -1
        gUniqSchema(u) = ExfMapGet(colIndex, nm)
        gUniqAncestor(u) = (ExfMapGet(ancestorIndex, nm) >= 0)
        ' Ecart assume: the online engine sorts rows by an _order column; in the
        ' workbook, rows are sorted in Excel and the column is refused.
        If nm = "_order" Then
            ExfSetError "errOrderColumn"
            Exit Function
        End If
        gUniqKind(u) = EXF_KIND_SKIP
        gUniqColumn(u) = -1
        If nm <> "_type" Then
            gUniqColumn(u) = ExfMapGet(colIndex, nm)
            If gUniqColumn(u) >= 0 Then
                gUniqKind(u) = EXF_KIND_COL
            ElseIf ExfMapGet(ancestorIndex, nm) < 0 Then
                If ExfIsXmlName(nm) Then gUniqKind(u) = EXF_KIND_NEW Else gUniqKind(u) = EXF_KIND_BAD
            End If
        End If
    Next u

    ReDim gIsSpace(0 To 65535)
    For k = 0 To p.spaceCount - 1
        gIsSpace(p.spaces(k)) = True
    Next k

    ' A header renamed by a find-and-replace: its column's repairs and checks
    ' (a renamed attribute's header is no longer an invalid name: macro 3.3).
    ExfEngineFindRenamed p, colIndex
    For c = 0 To nCols - 1
        If gUniqKind(mColUniq(c)) = EXF_KIND_BAD Then
            mBadCols(mBadCount) = c
            mBadCount = mBadCount + 1
        End If
    Next c

    ' Rows of these types left with only _type, _order or context cells are
    ' not written (execute.ts, value-repairs.ts withoutBareRows; BARETYPE).
    ExfMapInit mBareTypes, p.bareTypeCount + 1
    For k = 0 To p.bareTypeCount - 1
        ExfMapSet mBareTypes, p.strs(p.bareTypes(k)), 1
    Next k
    If p.bareTypeCount > 0 Then
        If p.isMultiTag Then
            mBareMulti = True
        Else
            mBareAll = (ExfMapGet(mBareTypes, p.strs(p.rowTag)) >= 0)
        End If
    End If
    mTypeCol = -1
    u = ExfMapGet(gUniqIndex, "_type")
    If u >= 0 Then mTypeCol = mUniqCol(u)
    ReDim mBareSkip(0 To gUniqCount - 1)
    For u = 0 To gUniqCount - 1
        mBareSkip(u) = (gUniqName(u) = "_type" Or gUniqName(u) = "_order" Or gUniqAncestor(u))
    Next u

    ReDim gVals(0 To gUniqCount - 1, 0 To 1023)
    ReDim gSheetRow(0 To 1023)
    ReDim gRowDirty(0 To 1023)
    ExfEngineStart = True
End Function

' One sheet row, cells already turned into text. An entirely empty row is
' skipped (reconstruct.ts parseCsvRecords). A copy of a name that differs from
' its leftmost column is counted, once per row (the site's "duplicate") -
' before a row left bare is dropped (BARETYPE), as the site counts them while
' it reads the CSV; a row that may hold a character XML forbids is marked for
' ExfEngineBuild.
Public Sub ExfEngineAddRow(ByRef rowCells() As String, ByVal sheetRow As Long)
    Dim c As Long, u As Long, n As Long, cap As Long, e As Long, bare As Boolean
    For c = 0 To mCols - 1
        If Len(rowCells(c)) > 0 Then Exit For
    Next c
    If c = mCols Then Exit Sub
    For e = 0 To mExtraCount - 1
        c = mExtraCols(e)
        u = mColUniq(c)
        If rowCells(c) <> rowCells(mUniqCol(u)) Then
            If mDupLast(u) <> sheetRow Then
                mDupLast(u) = sheetRow
                If gDupCount(u) < 3 Then gDupRows(u, gDupCount(u)) = sheetRow
                gDupCount(u) = gDupCount(u) + 1
            End If
        End If
    Next e
    bare = mBareAll
    If mBareMulti Then
        If mTypeCol >= 0 Then
            bare = (ExfMapGet(mBareTypes, ExfTrim(rowCells(mTypeCol), gIsSpace)) >= 0)
        Else
            bare = (ExfMapGet(mBareTypes, vbNullString) >= 0)
        End If
    End If
    If bare Then
        For u = 0 To gUniqCount - 1
            If Not mBareSkip(u) Then
                If Len(rowCells(mUniqCol(u))) > 0 Then
                    bare = False
                    Exit For
                End If
            End If
        Next u
        If bare Then Exit Sub
    End If
    For c = 0 To mBadCount - 1
        If Len(rowCells(mBadCols(c))) > 0 Then mBadData(mBadCols(c)) = True
    Next c
    n = gRowCount
    cap = UBound(gSheetRow) + 1
    If n = cap Then
        ReDim Preserve gVals(0 To gUniqCount - 1, 0 To 2 * cap - 1)
        ReDim Preserve gSheetRow(0 To 2 * cap - 1)
        ReDim Preserve gRowDirty(0 To 2 * cap - 1)
    End If
    For u = 0 To gUniqCount - 1
        gVals(u, n) = rowCells(mUniqCol(u))
    Next u
    gRowDirty(n) = ExfMayHoldInvalid(Join(rowCells, vbNullString))
    If gRowDirty(n) Then gAnyDirty = True
    gSheetRow(n) = sheetRow
    gRowCount = n + 1
End Sub

' Letter of the sheet column a unique name is read from (its leftmost).
Public Function ExfEngineLetter(ByVal u As Long) As String
    ExfEngineLetter = ExfColumnLetters(mUniqCol(u) + 1)
End Function

' Letters of the columns of a unique name, in the sheet's order ("D, W"), the
' first 4 then ", ..." (report.ts letterList).
Public Function ExfEngineLetters(ByVal u As Long) As String
    Dim c As Long, s As String, shown As Long
    For c = 0 To mCols - 1
        If mColUniq(c) = u Then
            If shown = 4 Then
                s = s & ", " & ChrW(8230)
                Exit For
            End If
            If Len(s) > 0 Then s = s & ", "
            s = s & ExfColumnLetters(c + 1)
            shown = shown + 1
        End If
    Next c
    ExfEngineLetters = s
End Function

' Ecart assume: the online engine silently drops a column whose name can't be
' an element; the macro stops, so no typed data is lost unseen.
Public Function ExfEngineCheckColumns() As Boolean
    Dim c As Long
    For c = 0 To mCols - 1
        If mBadData(c) Then
            ExfSetError "errHeaderInvalid", "column", ExfColumnLetters(c + 1), "name", mHeaders(c)
            Exit Function
        End If
    Next c
    ExfEngineCheckColumns = True
End Function

' The plan's CASE table by code unit, for ExfUpperForTokens.
Public Sub ExfEngineLoadCase(ByRef p As ExfPlan)
    Dim i As Long
    ReDim mHasUpper(0 To 65535)
    ReDim mUpper(0 To 65535)
    For i = 0 To p.caseCount - 1
        mHasUpper(p.caseMap(2 * i)) = True
        mUpper(p.caseMap(2 * i)) = p.strs(p.caseMap(2 * i + 1))
    Next i
End Sub

' = execute.ts renamedOf (value-repairs.ts renamedColumns): the headers
' renamed in the sheet by a find-and-replace that hit a header too, by unique
' name (gUniqRenamed: the COL entry it stands in for). Only with sourceOrder
' (the sheet's columns are _type, the context columns, then the schema, in
' the plan's order - a name listed twice counted once, at its first place:
' the schema of a file with several row types holds _type too), and only when
' every other header is in its place: as many headers as expected, each one
' its own column at its place, or a name the plan doesn't know, met once, at
' the place of a schema column other than _type the sheet no longer has - at
' most half of them. Linear in the columns.
Private Sub ExfEngineFindRenamed(ByRef p As ExfPlan, ByRef colIndex As ExfStrMap)
    Dim expected() As String, total As Long, k As Long, c As Long, u As Long, found As Long
    Dim known As ExfStrMap, times() As Long, hit() As Long
    ReDim gUniqRenamed(0 To gUniqCount - 1)
    ReDim gUniqAttr(0 To gUniqCount - 1)
    ReDim hit(0 To gUniqCount - 1)
    For u = 0 To gUniqCount - 1
        gUniqRenamed(u) = -1
        hit(u) = -1
    Next u
    ExfMapInit mAliasU, 16
    If Not p.sourceOrder Then Exit Sub
    total = p.ancestorCount + p.colCount + 1
    If mCols = 0 Or mCols > total Then Exit Sub
    ReDim expected(0 To total - 1)
    ExfMapInit known, total
    total = 0
    If p.isMultiTag Then ExfEngineExpect expected, total, known, "_type"
    For k = 0 To p.ancestorCount - 1
        ExfEngineExpect expected, total, known, p.strs(p.ancestorCols(k))
    Next k
    For k = 0 To p.colCount - 1
        ExfEngineExpect expected, total, known, p.strs(p.colName(k))
    Next k
    If total <> mCols Then Exit Sub
    ' How many sheet columns carry each name.
    ReDim times(0 To gUniqCount - 1)
    For c = 0 To mCols - 1
        times(mColUniq(c)) = times(mColUniq(c)) + 1
    Next c
    For c = 0 To mCols - 1
        If mHeaders(c) <> expected(c) Then
            k = ExfMapGet(colIndex, expected(c))
            If Len(ExfTrim(mHeaders(c), gIsSpace)) = 0 Then Exit Sub
            If ExfMapGet(known, mHeaders(c)) >= 0 Then Exit Sub
            If times(mColUniq(c)) <> 1 Then Exit Sub
            If ExfMapGet(gUniqIndex, expected(c)) >= 0 Then Exit Sub
            If k < 0 Or expected(c) = "_type" Then Exit Sub
            hit(mColUniq(c)) = k
            found = found + 1
        End If
    Next c
    If found * 2 > mCols Then Exit Sub
    ' Only a header written under its new name is a rename (macro 3.3): an
    ' element's name, or a renamed attribute's header (ExfEngineRenamedAttr):
    ' its kind is then EXF_KIND_RATTR, its new name in gUniqAttr.
    For u = 0 To gUniqCount - 1
        If hit(u) >= 0 And gUniqKind(u) = EXF_KIND_BAD Then
            gUniqAttr(u) = ExfEngineRenamedAttr(p, gUniqName(u), hit(u))
            If Len(gUniqAttr(u)) > 0 Then gUniqKind(u) = EXF_KIND_RATTR Else hit(u) = -1
        End If
        gUniqRenamed(u) = hit(u)
        If hit(u) >= 0 Then ExfMapSet mAliasU, p.strs(p.colName(hit(u))), u
    Next u
End Sub

' = execute.ts renamedAttributeOf (value-repairs.ts renamedAttributeName): the
' attribute a renamed header writes, "" for none (macro 3.3). COL entry k is an
' attribute's, and the header keeps its element's path - everything up to the
' source name's last "@" (an attribute name has none) - followed by a name XML
' accepts, other than the attributes that name the element (the qualifiers of
' the column's last segment).
Private Function ExfEngineRenamedAttr(ByRef p As ExfPlan, ByRef header As String, ByVal k As Long) As String
    Dim src As String, atPos As Long, nm As String, s As Long, q As Long
    If p.colKind(k) <> EXF_COL_ATTR Then Exit Function
    src = p.strs(p.colName(k))
    atPos = InStrRev(src, "@")
    If atPos = 0 Then Exit Function
    If Len(header) <= atPos Then Exit Function
    If Left$(header, atPos) <> Left$(src, atPos) Then Exit Function
    nm = Mid$(header, atPos + 1)
    If Not ExfIsXmlName(nm) Then Exit Function
    If p.colSegCount(k) > 0 Then
        s = p.colSegStart(k) + p.colSegCount(k) - 1
        If p.segQualAttr(s) >= 0 Then
            If p.strs(p.segQualAttr(s)) = nm Then Exit Function
        End If
        If p.segQualStart(s) >= 0 Then
            For q = p.segQualStart(s) To p.segQualStart(s) + p.segQualCount(s) - 1
                If p.strs(p.segQuals(2 * q)) = nm Then Exit Function
            Next q
        End If
    End If
    ExfEngineRenamedAttr = nm
End Function

' One more name of the sheet's expected columns, unless it is listed already.
Private Sub ExfEngineExpect(ByRef expected() As String, ByRef total As Long, ByRef known As ExfStrMap, ByVal nm As String)
    If ExfMapGet(known, nm) >= 0 Then Exit Sub
    ExfMapSet known, nm, 1
    expected(total) = nm
    total = total + 1
End Sub

' A table entry of a column, for the column and for a header renamed from it
' (execute.ts changesOf, entryOf): the first entry wins.
Private Sub ExfEngineMark(ByRef at() As Long, ByVal nm As String, ByVal entry As Long)
    Dim u As Long
    u = ExfMapGet(gUniqIndex, nm)
    If u >= 0 Then
        If at(u) < 0 Then at(u) = entry
    End If
    u = ExfMapGet(mAliasU, nm)
    If u >= 0 Then
        If at(u) < 0 Then at(u) = entry
    End If
End Sub

' One more entry of the question: its line among the first 3; zerosOnly
' turns False on an entry that is not of leading zeros.
Private Sub ExfEngineAddChange(ByRef lst As String, ByRef total As Long, ByRef zerosOnly As Boolean, _
                               ByVal lineText As String, ByVal isZeros As Boolean)
    If Not isZeros Then zerosOnly = False
    If total < 3 Then
        If Len(lst) > 0 Then lst = lst & vbLf
        lst = lst & lineText
    End If
    total = total + 1
End Sub

' = execute.ts changesOf (reconstruct.ts spreadsheetChanges, value-repairs.ts
' zerosRemoved, decimalsRemoved, scientificCodesExpanded): the values a
' spreadsheet changed that the rebuild can't put back, column by column in
' the sheet's order, each column's kinds in the site's order:
'  - a spreadsheet's error word (ERRWORD, "Err:5xx") in a column of the schema
'    whose source held none (ERRKEEP), with META errorWords only;
'  - digit codes of several widths that started with zeros in the source
'    (ZEROCODE), none left - at least one cell is digits only and not one of
'    them starts with 0 ("0" alone doesn't count); with the list of the
'    source's zero-led values without their zeros (ZEROSTRIP), only one of
'    those back as it is ("7" for "007") counts;
'  - decimal numbers of several widths that ended with a zero in the source
'    (DECCODE), none left so, one of their values without its zeros back
'    (DECSTRIP);
'  - codes like "12E3" (SCICODE), none left so, a cell holding the number one
'    stood for (SCINUM, ExfPlainNumber).
' A renamed header is looked at as its column. On the raw cells, before
' ExfEngineBuild: the site stops first. Builds the list of the question
' (report.ts askChangesList): askLeadingZeros when every entry is of leading
' zeros, else askValuesChanged.
Public Sub ExfEngineFindChanges(ByRef p As ExfPlan)
    Dim u As Long, n As Long, k As Long, i As Long, z As Long, d As Long, q As Long, cnt As Long, total As Long
    Dim v As String, src As String, sample As String, lst As String, num As String
    Dim zero As Boolean, stillCode As Boolean, zerosOnly As Boolean
    Dim zeroAt() As Long, decAt() As Long, sciAt() As Long, rows3() As Long
    Dim stripped As ExfStrMap, decStripped As ExfStrMap, sciNumbers As ExfStrMap, errWords As ExfStrMap, errKeep As ExfStrMap

    ReDim rows3(0 To 2)
    ReDim zeroAt(0 To gUniqCount - 1)
    ReDim decAt(0 To gUniqCount - 1)
    ReDim sciAt(0 To gUniqCount - 1)
    For u = 0 To gUniqCount - 1
        zeroAt(u) = -1
        decAt(u) = -1
        sciAt(u) = -1
    Next u
    For z = 0 To p.zeroCodeCount - 1
        ExfEngineMark zeroAt, p.strs(p.zeroCodeCol(z)), z
    Next z
    For d = 0 To p.decCodeCount - 1
        ExfEngineMark decAt, p.strs(p.decCodeCol(d)), d
    Next d
    For q = 0 To p.sciCount - 1
        ExfEngineMark sciAt, p.strs(p.sciCol(q)), q
    Next q
    ' The lists, by entry: "entry<TAB>value".
    ExfMapInit stripped, p.zeroStripTotal + 1
    For z = 0 To p.zeroCodeCount - 1
        For k = 0 To p.zeroCodeStripCount(z) - 1
            ExfMapSet stripped, CStr(z) & vbTab & p.strs(p.zeroStrips(p.zeroCodeStripStart(z) + k)), 1
        Next k
    Next z
    ExfMapInit decStripped, p.decStripTotal + 1
    For d = 0 To p.decCodeCount - 1
        For k = 0 To p.decStripCount(d) - 1
            ExfMapSet decStripped, CStr(d) & vbTab & p.strs(p.decStrips(p.decStripStart(d) + k)), 1
        Next k
    Next d
    ExfMapInit sciNumbers, p.sciNumTotal + 1
    For q = 0 To p.sciCount - 1
        For k = 0 To p.sciNumCount(q) - 1
            ExfMapSet sciNumbers, CStr(q) & vbTab & p.strs(p.sciNums(p.sciNumStart(q) + k)), 1
        Next k
    Next q
    ExfMapInit errWords, p.errWordCount + 1
    For k = 0 To p.errWordCount - 1
        ExfMapSet errWords, p.strs(p.errWords(k)), 1
    Next k
    ExfMapInit errKeep, p.errKeepCount + 1
    For k = 0 To p.errKeepCount - 1
        ExfMapSet errKeep, p.strs(p.errKeep(k)), 1
    Next k

    zerosOnly = True
    For u = 0 To gUniqCount - 1
        ' Error words: the schema's columns, a renamed header as its column.
        If p.errorWords And (gUniqSchema(u) >= 0 Or gUniqRenamed(u) >= 0) Then
            If gUniqRenamed(u) >= 0 Then src = p.strs(p.colName(gUniqRenamed(u))) Else src = gUniqName(u)
            If ExfMapGet(errKeep, src) < 0 Then
                cnt = 0
                For n = 0 To gRowCount - 1
                    If Len(gVals(u, n)) >= 4 Then
                        If ExfIsErrorWord(gVals(u, n), gIsSpace, errWords) Then
                            If cnt = 0 Then sample = gVals(u, n)
                            If cnt < 3 Then rows3(cnt) = gSheetRow(n)
                            cnt = cnt + 1
                        End If
                    End If
                Next n
                If cnt > 0 Then
                    ExfEngineAddChange lst, total, zerosOnly, ExfFill(ExfMessageText("listErrorWord"), "column", ExfBuildAskName(gUniqName(u)), _
                        "cells", ExfBuildAskCells(ExfEngineLetter(u), rows3, cnt), "sample", ExfBuildAskName(sample)), False
                End If
            End If
        End If
        ' Leading zeros.
        z = zeroAt(u)
        If z >= 0 Then
            zero = False
            sample = vbNullString
            For n = 0 To gRowCount - 1
                v = gVals(u, n)
                If ExfIsDigits(v) Then
                    If Len(v) > 1 And Left$(v, 1) = "0" Then
                        zero = True
                        Exit For
                    End If
                    If Len(sample) = 0 Then
                        If p.zeroCodeStripStart(z) < 0 Then
                            sample = v
                        ElseIf ExfMapGet(stripped, CStr(z) & vbTab & v) >= 0 Then
                            sample = v
                        End If
                    End If
                End If
            Next n
            If Not zero And Len(sample) > 0 Then
                ExfEngineAddChange lst, total, zerosOnly, ExfFill(ExfMessageText("listLeadingZeros"), "column", ExfBuildAskName(gUniqName(u)), _
                    "letter", ExfEngineLetter(u), "count", CStr(p.zeroCodeHad(z)), "sample", ExfBuildAskName(sample)), True
            End If
        End If
        ' Decimal zeros.
        d = decAt(u)
        If d >= 0 Then
            zero = False
            cnt = 0
            For n = 0 To gRowCount - 1
                k = Len(gVals(u, n))
                If k > 0 And k <= 20 Then
                    v = gVals(u, n)
                    i = ExfDecimalsOf(v)
                    If i > 0 And Right$(v, 1) = "0" Then
                        zero = True
                        Exit For
                    End If
                    If i >= 0 Then
                        If ExfMapGet(decStripped, CStr(d) & vbTab & v) >= 0 Then
                            If cnt = 0 Then sample = v
                            If cnt < 3 Then rows3(cnt) = gSheetRow(n)
                            cnt = cnt + 1
                        End If
                    End If
                End If
            Next n
            If Not zero And cnt > 0 Then
                ExfEngineAddChange lst, total, zerosOnly, ExfFill(ExfMessageText("listDecimals"), "column", ExfBuildAskName(gUniqName(u)), _
                    "cells", ExfBuildAskCells(ExfEngineLetter(u), rows3, cnt), "sample", ExfBuildAskName(sample)), False
            End If
        End If
        ' Codes like "12E3" written as numbers.
        q = sciAt(u)
        If q >= 0 Then
            stillCode = False
            cnt = 0
            For n = 0 To gRowCount - 1
                If Len(gVals(u, n)) > 0 Then
                    v = gVals(u, n)
                    If ExfIsScientificCode(v) Then
                        stillCode = True
                        Exit For
                    End If
                    num = ExfPlainNumber(v)
                    If Len(num) > 0 Then
                        If ExfMapGet(sciNumbers, CStr(q) & vbTab & num) >= 0 Then
                            If cnt = 0 Then sample = v
                            If cnt < 3 Then rows3(cnt) = gSheetRow(n)
                            cnt = cnt + 1
                        End If
                    End If
                End If
            Next n
            If Not stillCode And cnt > 0 Then
                ExfEngineAddChange lst, total, zerosOnly, ExfFill(ExfMessageText("listScientificCode"), "column", ExfBuildAskName(gUniqName(u)), _
                    "cells", ExfBuildAskCells(ExfEngineLetter(u), rows3, cnt), "sample", ExfBuildAskName(sample)), False
            End If
        End If
    Next u
    If total > 3 Then lst = lst & vbLf & ExfFill(ExfMessageText("listMoreLines"), "count", CStr(total))
    gAskChanges = lst
    If zerosOnly Then gAskChangesKey = "askLeadingZeros" Else gAskChangesKey = "askValuesChanged"
End Sub

' = execute.ts padDecimalsOf, padZerosOf and repairSpellings (value-repairs.ts
' padDecimals, padZeros, repairBooleans), once the cells are cleaned
' (ExfBuildFindCells): decimal numbers of one width (FIXDEC) given back the
' zeros a spreadsheet dropped and the column's separator ("19.9", "24,9" ->
' "19.90", "24.90"); the codes of one width (ZEROPAD) shorter than it, digits
' only, given their leading zeros back; then in each column that held true /
' false (BOOLSPELL) a spreadsheet's boolean word (SPELLWORD: TRUE, VRAI,
' PRAVDA..., in any case, spaces around) back to the source's spelling -
' except a word the column held as text, and a value exactly as the source
' wrote it (BOOLKEEP) unless not one cell of the column is left in the
' source's spelling. Each repair applies to its column and to a header
' renamed from it (mAliasU).
Public Sub ExfEngineRepairValues(ByRef p As ExfPlan)
    Dim z As Long, u As Long, n As Long, b As Long, j As Long, f As Long, pass As Long
    Dim w As Long, cnt As Long, v As String, words As ExfStrMap
    For f = 0 To p.fixDecCount - 1
        ExfEnginePadDecimals p, f, ExfMapGet(gUniqIndex, p.strs(p.fixDecCol(f)))
        ExfEnginePadDecimals p, f, ExfMapGet(mAliasU, p.strs(p.fixDecCol(f)))
    Next f

    ' Every column of ZEROPAD, then the renamed headers, in the same order.
    For pass = 0 To 1
        For z = 0 To p.zeroPadCount - 1
            If pass = 0 Then
                u = ExfMapGet(gUniqIndex, p.strs(p.zeroPadCol(z)))
            Else
                u = ExfMapGet(mAliasU, p.strs(p.zeroPadCol(z)))
            End If
            If u >= 0 Then
                w = p.zeroPadWidth(z)
                cnt = 0
                For n = 0 To gRowCount - 1
                    v = gVals(u, n)
                    If Len(v) > 0 And Len(v) < w Then
                        If ExfIsDigits(v) Then
                            gVals(u, n) = String$(w - Len(v), "0") & v
                            cnt = cnt + 1
                        End If
                    End If
                Next n
                If cnt > 0 Then
                    If Len(gPadded) > 0 Then gPadded = gPadded & ","
                    gPadded = gPadded & gUniqName(u) & "=" & CStr(cnt)
                End If
            End If
        Next z
    Next pass

    If p.spellCount = 0 Then Exit Sub
    ExfMapInit words, p.spellWordCount
    For j = 0 To p.spellWordCount - 1
        ExfMapSet words, p.strs(p.spellWords(2 * j)), p.spellWords(2 * j + 1)
    Next j
    For b = 0 To p.spellCount - 1
        ExfEngineSpellColumn p, b, ExfMapGet(gUniqIndex, p.strs(p.spellCol(b))), words
        ExfEngineSpellColumn p, b, ExfMapGet(mAliasU, p.strs(p.spellCol(b))), words
    Next b
End Sub

' = execute.ts padDecimalsOf, one column (u < 0: not in the sheet). Only plain
' numbers of no more decimals than the column's ("1,250" is left as it is).
Private Sub ExfEnginePadDecimals(ByRef p As ExfPlan, ByVal f As Long, ByVal u As Long)
    Dim n As Long, want As Long, have As Long, sep As String, v As String
    If u < 0 Then Exit Sub
    want = p.fixDecDecimals(f)
    sep = p.strs(p.fixDecSep(f))
    For n = 0 To gRowCount - 1
        If Len(gVals(u, n)) > 0 And Len(gVals(u, n)) <= 20 Then
            v = gVals(u, n)
            have = ExfDecimalsOf(v)
            If have >= 0 And have <= want Then
                If have > 0 And Mid$(v, Len(v) - have, 1) <> sep Then
                    gVals(u, n) = Left$(v, Len(v) - have - 1) & sep & Right$(v, have) & String$(want - have, "0")
                ElseIf have < want Then
                    If have > 0 Then
                        gVals(u, n) = v & String$(want - have, "0")
                    Else
                        gVals(u, n) = v & sep & String$(want - have, "0")
                    End If
                End If
            End If
        End If
    Next n
End Sub

' = execute.ts repairSpelling: the BOOLSPELL entry b on unique column u (u < 0:
' not in the sheet).
Private Sub ExfEngineSpellColumn(ByRef p As ExfPlan, ByVal b As Long, ByVal u As Long, ByRef words As ExfStrMap)
    Dim n As Long, j As Long, k1 As Long, k2 As Long, bv As Long
    Dim v As String, t As String, f As String, wd As String
    Dim rewritten As Boolean, kept As Boolean, asText As Boolean
    If u < 0 Then Exit Sub
    t = p.strs(p.spellTrue(b))
    f = p.strs(p.spellFalse(b))
    k1 = p.spellKeepStart(b)
    k2 = k1 + p.spellKeepCount(b) - 1
    rewritten = True
    For n = 0 To gRowCount - 1
        If gVals(u, n) = t Or gVals(u, n) = f Then
            rewritten = False
            Exit For
        End If
    Next n
    For n = 0 To gRowCount - 1
        v = gVals(u, n)
        If Len(v) > 0 And v <> t And v <> f Then
            kept = False
            For j = k1 To k2
                If p.strs(p.keepValue(j)) = v Then
                    kept = Not (rewritten And p.keepIsTrueFalse(j) = 1)
                    Exit For
                End If
            Next j
            If Not kept And Len(v) <= 16 Then
                wd = ExfUpperForTokens(ExfTrim(v, gIsSpace), mHasUpper, mUpper)
                bv = ExfMapGet(words, wd)
                If bv >= 0 Then
                    asText = False
                    For j = k1 To k2
                        If p.keepWord(j) >= 0 Then
                            If p.strs(p.keepWord(j)) = wd Then
                                asText = True
                                Exit For
                            End If
                        End If
                    Next j
                    If Not asText Then
                        If bv = 1 Then gVals(u, n) = t Else gVals(u, n) = f
                    End If
                End If
            End If
        End If
    Next n
End Sub

' Booleans turned TRUE/FALSE or VRAI/FAUX by a spreadsheet, in the columns that
' held only true/false in the source (plan tables BOOLCOL, BOOLTOKEN, CASE) -
' those the source's spellings leave (ExfEngineRepairValues).
Public Sub ExfEngineNormalizeBooleans(ByRef p As ExfPlan)
    Dim b As Long, i As Long, n As Long, u As Long, mapped As Long, v As String
    Dim tokens As ExfStrMap
    ExfMapInit tokens, p.boolTokenCount
    For i = 0 To p.boolTokenCount - 1
        ExfMapSet tokens, p.strs(p.boolTokens(2 * i)), p.boolTokens(2 * i + 1)
    Next i
    For b = 0 To p.boolColCount - 1
        u = ExfMapGet(gUniqIndex, p.strs(p.boolCols(b)))
        If u >= 0 Then
            For n = 0 To gRowCount - 1
                v = gVals(u, n)
                If Len(v) > 0 Then
                    If v <> "true" And v <> "false" Then
                        mapped = ExfMapGet(tokens, ExfUpperForTokens(ExfTrim(v, gIsSpace), mHasUpper, mUpper))
                        If mapped >= 0 Then gVals(u, n) = p.strs(mapped)
                    End If
                End If
            Next n
        End If
    Next b
End Sub

Public Function ExfEngineRowCount() As Long
    ExfEngineRowCount = gRowCount
End Function

' Columns written as new elements, comma-separated (message successNewColumns).
Public Function ExfEngineNewColumns() As String
    ExfEngineNewColumns = gNewColumns
End Function

' Columns whose filled cells were left out after Yes to askCellsIgnored
' (successIgnoredColumns).
Public Function ExfEngineIgnoredColumns() As String
    ExfEngineIgnoredColumns = gIgnoredColumns
End Function

' The list of the question askCellsIgnored, "" when there is no question.
Public Function ExfEngineAskIgnored() As String
    ExfEngineAskIgnored = gAskIgnored
End Function

' Its key: askCellsIgnored, or askRenamed when every line is a renamed header.
Public Function ExfEngineAskIgnoredKey() As String
    ExfEngineAskIgnoredKey = gAskIgnoredKey
End Function

' The list of the question askInvalidCharacters, "" when there is no question.
Public Function ExfEngineAskInvalid() As String
    ExfEngineAskInvalid = gAskInvalid
End Function

' The list of the question of values changed (ExfEngineFindChanges), ""
' when there is no question.
Public Function ExfEngineAskChanges() As String
    ExfEngineAskChanges = gAskChanges
End Function

' Its key: askLeadingZeros, or askValuesChanged when another kind is listed.
Public Function ExfEngineAskChangesKey() As String
    ExfEngineAskChangesKey = gAskChangesKey
End Function

' Codes given their leading zeros back: "column=cells,..." (message
' successPaddedZeros, and the test benches' report).
Public Function ExfEnginePadded() As String
    ExfEnginePadded = gPadded
End Function

' Frees the memory held between two runs.
Public Sub ExfEngineReset()
    mCols = 0
    gUniqCount = 0
    mBadCount = 0
    mExtraCount = 0
    gRowCount = 0
    gAnyDirty = False
    gNewColumns = vbNullString
    gIgnoredColumns = vbNullString
    gAskIgnored = vbNullString
    gAskIgnoredKey = "askCellsIgnored"
    gAskInvalid = vbNullString
    gAskChanges = vbNullString
    gAskChangesKey = "askLeadingZeros"
    gPadded = vbNullString
    mBareAll = False
    mBareMulti = False
    mTypeCol = -1
    Erase mHeaders, mColUniq, mBadCols, mBadData, mUniqCol, mExtraCols, mDupLast, mHasUpper, mUpper, mBareSkip
    Erase gUniqName, gUniqKind, gUniqColumn, gUniqSchema, gUniqAncestor, gVals, gSheetRow, gRowDirty, gDupCount, gDupRows, gIsSpace, gUniqRenamed, gUniqAttr
    ExfMapInit gUniqIndex, 16
    ExfMapInit mAliasU, 16
    ExfMapInit mBareTypes, 16
    ExfTreeReset
End Sub
modExfEntry.basEntry point: the "Generate XML" button22 lines
Attribute VB_Name = "modExfEntry"
' ExcelifyXML - the workbook's macro: rebuilds the XML file from the Data sheet.
'
' What it does, in order:
'   1. reads the structure stored by the website in the hidden sheet _excelify;
'   2. reads the Data sheet (row 1 = technical names, row 2 = your labels,
'      never read, data below);
'   3. rebuilds the XML exactly as the website's online reconstruction does;
'   4. asks where to save it and writes that single file (UTF-8).
' Nothing else: no network, no automatic start, no other file read or changed.
' Source code and explanations: https://www.excelifyxml.com/excel-macro
'
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary

' The "Generate XML" button (also in Alt+F8 > Macros) - the only macro this
' workbook offers: every other module is private to it.
Public Sub ExcelifyGenererXML()
    ExfRunBook ThisWorkbook, vbNullString, True
End Sub
modExfMap.basInternal dictionary (case-sensitive lookup table)114 lines
Attribute VB_Name = "modExfMap"
' ExcelifyXML - case-sensitive map from text to number (StrMap in
' src/lib/excel-macro/engine/execute.ts). Scripting.Dictionary only exists on
' Windows and a Collection ignores case, so the macro has its own: a chained
' hash table held in plain arrays.
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary
Option Private Module

Public Type ExfStrMap
    keys() As String
    vals() As Long
    hashes() As Long
    nxt() As Long           ' next entry in the same bucket, -1 at the end
    buckets() As Long       ' first entry of each bucket, -1 when empty
    count As Long
    mask As Long            ' number of buckets - 1 (a power of two)
End Type

' Prime below 2^20: h * 33 + 255 stays far below the 2^31 limit of a Long.
Private Const HASH_MOD As Long = 1048573

Public Sub ExfMapInit(ByRef m As ExfStrMap, Optional ByVal capacity As Long = 16)
    Dim size As Long, i As Long
    size = 16
    Do While size < capacity And size < 1048576
        size = size * 2
    Loop
    ReDim m.keys(0 To size - 1)
    ReDim m.vals(0 To size - 1)
    ReDim m.hashes(0 To size - 1)
    ReDim m.nxt(0 To size - 1)
    ReDim m.buckets(0 To size - 1)
    For i = 0 To size - 1
        m.buckets(i) = -1
    Next i
    m.count = 0
    m.mask = size - 1
End Sub

' Hash of the UTF-16 code units (read as bytes: no character is skipped).
Private Function ExfHash(ByRef key As String) As Long
    Dim b() As Byte, i As Long, h As Long
    If Len(key) = 0 Then Exit Function
    b = key
    h = 5381
    For i = 0 To UBound(b)
        h = (h * 33 + b(i)) Mod HASH_MOD
    Next i
    ExfHash = h
End Function

' Value stored for key, or -1 when absent.
Public Function ExfMapGet(ByRef m As ExfStrMap, ByRef key As String) As Long
    Dim e As Long, h As Long
    h = ExfHash(key)
    e = m.buckets(h And m.mask)
    Do While e >= 0
        If m.hashes(e) = h Then
            If m.keys(e) = key Then
                ExfMapGet = m.vals(e)
                Exit Function
            End If
        End If
        e = m.nxt(e)
    Loop
    ExfMapGet = -1
End Function

Public Sub ExfMapSet(ByRef m As ExfStrMap, ByRef key As String, ByVal aValue As Long)
    Dim e As Long, h As Long, b As Long
    h = ExfHash(key)
    e = m.buckets(h And m.mask)
    Do While e >= 0
        If m.hashes(e) = h Then
            If m.keys(e) = key Then
                m.vals(e) = aValue
                Exit Sub
            End If
        End If
        e = m.nxt(e)
    Loop
    If m.count > m.mask Then ExfMapGrow m
    e = m.count
    m.keys(e) = key
    m.vals(e) = aValue
    m.hashes(e) = h
    b = h And m.mask
    m.nxt(e) = m.buckets(b)
    m.buckets(b) = e
    m.count = e + 1
End Sub

' Twice as many buckets (and entry slots), entries re-chained.
Private Sub ExfMapGrow(ByRef m As ExfStrMap)
    Dim size As Long, i As Long, b As Long
    size = (m.mask + 1) * 2
    ReDim Preserve m.keys(0 To size - 1)
    ReDim Preserve m.vals(0 To size - 1)
    ReDim Preserve m.hashes(0 To size - 1)
    ReDim Preserve m.nxt(0 To size - 1)
    ReDim m.buckets(0 To size - 1)
    m.mask = size - 1
    For i = 0 To size - 1
        m.buckets(i) = -1
    Next i
    For i = 0 To m.count - 1
        b = m.hashes(i) And m.mask
        m.nxt(i) = m.buckets(b)
        m.buckets(b) = i
    Next i
End Sub
modExfPlan.basReading the workbook's structure information511 lines
Attribute VB_Name = "modExfPlan"
' ExcelifyXML - reads the plan: everything needed to rebuild the XML, stored by
' the website in the hidden sheet "_excelify" as blocks of cells (numbers and
' one pool of strings, no JSON to parse). Port of readPlanSheet in
' src/lib/excel-macro/xlsx/plan-sheet.ts; the tables are described in
' src/lib/excel-macro/engine/plan.ts.
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary
Option Private Module

Public Const EXF_PLAN_MARKER As String = "EXCELIFY"
Public Const EXF_PLAN_FORMAT As Long = 5        ' newest plan format this macro reads
Public Const EXF_MACRO_VERSION As Long = 6      ' compared with the plan's C1 (macro 3.3)

' Column kinds of the COL table.
Public Const EXF_COL_TEXT As Long = 1
Public Const EXF_COL_ATTR As Long = 2
Public Const EXF_COL_NONE As Long = 3
Public Const EXF_COL_LIST As Long = 4           ' plan format 5: one element per line of the cell

' Every array is 0-based and always allocated (one spare slot), its length in
' the matching count. Pair tables are flat: pair i = (x(2 * i), x(2 * i + 1)).
Public Type ExfPlan
    planFormat As Long
    strs() As String            ' string pool, every other table refers to it
    strCount As Long
    indent As Long
    prologue() As Long          ' declaration line, then header comments
    prologueCount As Long
    rootName As Long
    rootAttrs() As Long         ' pairs (name, value)
    rootAttrCount As Long
    isMultiTag As Boolean
    rowTag As Long
    sourceOrder As Boolean      ' fields in the COL table's order (the source's), then the added columns
    cleanOutput As Boolean      ' a string holds a character XML forbids: cleaned when written
    compact As Boolean          ' an occurrence left with nothing in it is not written (value repairs)
    types() As Long             ' multi-tag rows: the known _type values
    typeScoped() As Long
    typeColStart() As Long
    typeColCount() As Long
    typeCount As Long
    typeCols() As Long
    typeColTotal As Long
    typeOrder() As Long         ' rows of several types: the source's order of types
    typeOrderCount As Long
    nodeName() As Long          ' element trees kept verbatim (root and wrapper siblings)
    nodeText() As Long
    nodeSelfClosing() As Long
    nodeSlot() As Long
    nodeAttrStart() As Long
    nodeAttrCount() As Long
    nodeChildStart() As Long
    nodeChildCount() As Long
    nodeCount As Long
    nodeAttrs() As Long         ' pairs (name, value)
    nodeAttrTotal As Long
    nodeChildren() As Long
    nodeChildTotal As Long
    rootList() As Long
    rootListCount As Long
    rootRowsAt As Long          ' rootList entries before the rows, the rest after; -1: all before
    wrapName() As Long          ' the elements between the root and the rows
    wrapSelfClosing() As Long
    wrapListStart() As Long
    wrapListCount() As Long
    wrapKeyStart() As Long
    wrapKeyCount() As Long
    wrapRowsAt() As Long        ' innermost level: siblings before the rows; -1: all
    wrapOptional() As Long      ' 1: some container of the level lacked an attribute (value repairs)
    wrapCount As Long
    wrapLists() As Long
    wrapListTotal As Long
    keyAttr() As Long
    keyColumn() As Long
    keyDefault() As Long
    keyOptional() As Long       ' 1: such an attribute, not written empty on a new container
    keyCount As Long
    instLevel() As Long         ' own siblings of each wrapper instance
    instKey() As Long
    instListStart() As Long
    instListCount() As Long
    instRowsAt() As Long        ' innermost level: the instance's siblings before the rows; -1: all
    instCount As Long
    instLists() As Long
    instListTotal As Long
    colName() As Long           ' how each known column reaches its element
    colKind() As Long
    colAttr() As Long
    colCdata() As Long
    colSegStart() As Long
    colSegCount() As Long
    colCount As Long
    segName() As Long
    segIndex() As Long
    segQualAttr() As Long
    segQualValue() As Long
    segQualStart() As Long      ' several attributes naming the element: first pair in segQuals, -1 none
    segQualCount() As Long
    segCount As Long
    segQuals() As Long          ' pairs (attribute, value); value -1: the attribute must be absent
    segQualTotal As Long
    ancestorCols() As Long
    ancestorCount As Long
    eaCol() As Long             ' value repairs: attribute columns written empty (COL entry, element)
    eaElement() As Long
    eaCount As Long
    eaUnderCol() As Long        ' the empty-attribute elements each COL entry goes through
    eaUnderElement() As Long
    eaUnderCount As Long
    trCol() As Long             ' text columns the source always filled (COL entry, element)
    trElement() As Long
    trCount As Long
    trUnderCol() As Long        ' the text-required elements each COL entry goes through
    trUnderElement() As Long
    trUnderCount As Long
    keepGaps() As Long          ' lists whose empty occurrences are written
    keepGapCount As Long
    zeroPadCol() As Long        ' codes of one width: leading zeros put back
    zeroPadWidth() As Long
    zeroPadCount As Long
    zeroCodeCol() As Long       ' codes of several widths: asked about when every zero is gone
    zeroCodeHad() As Long
    zeroCodeStripStart() As Long ' its zero-led values without their zeros in zeroStrips (-1: no list)
    zeroCodeStripCount() As Long
    zeroCodeCount As Long
    zeroStrips() As Long        ' ZEROSTRIP: asked about only when one of them is back
    zeroStripTotal As Long
    spellCol() As Long          ' columns that held true / false, the source's spellings
    spellTrue() As Long
    spellFalse() As Long
    spellKeepStart() As Long
    spellKeepCount() As Long
    spellCount As Long
    keepValue() As Long         ' values left as written
    keepIsTrueFalse() As Long
    keepWord() As Long
    keepCount As Long
    spellWords() As Long        ' pairs (spreadsheet boolean word, 1 | 0)
    spellWordCount As Long
    fixDecCol() As Long         ' format 4: decimal numbers of one width (column, decimals, separator)
    fixDecDecimals() As Long
    fixDecSep() As Long
    fixDecCount As Long
    decCodeCol() As Long        ' decimal numbers of several widths: asked about when every zero is gone
    decStripStart() As Long
    decStripCount() As Long
    decCodeCount As Long
    decStrips() As Long         ' DECSTRIP: their values without the decimal zeros
    decStripTotal As Long
    bareTypes() As Long         ' row types whose rows left with only _type or context cells are not written
    bareTypeCount As Long
    sciCol() As Long            ' codes like "12E3": asked about when written as numbers
    sciNumStart() As Long
    sciNumCount() As Long
    sciCount As Long
    sciNums() As Long           ' SCINUM: the numbers they stand for
    sciNumTotal As Long
    errorWords As Boolean       ' META: spreadsheet error words looked for
    errWords() As Long          ' ERRWORD: the error words that start with "#"
    errWordCount As Long
    errKeep() As Long           ' ERRKEEP: columns whose source held error words
    errKeepCount As Long
    selfClosing() As Long
    selfCloseCount As Long
    boolCols() As Long
    boolColCount As Long
    boolTokens() As Long        ' pairs (token, value)
    boolTokenCount As Long
    caseMap() As Long           ' pairs (code unit, uppercase string)
    caseCount As Long
    spaces() As Long
    spaceCount As Long
    locale As String            ' META
    sourceName As String
    outputName As String
End Type

' Table of contents of the plan sheet.
Private mSecName() As String
Private mSecFirst() As Long
Private mSecRows() As Long
Private mSecWidth() As Long
Private mSecTotal As Long

' Reads the plan into p; False when the message set by ExfSetError must be
' shown (errPlanMissing, errPlanTooNew). The macro messages (MSG section) are
' loaded first, so that even a refusal is shown in the workbook's language.
Public Function ExfReadPlan(ByVal ws As Worksheet, ByRef p As ExfPlan) As Boolean
    Dim head As Variant, toc As Variant, block As Variant, i As Long, n As Long

    head = ExfBlock(ws, 1, 1, 4)
    If VarType(head(1, 1)) <> vbString Then GoTo Missing
    If head(1, 1) <> EXF_PLAN_MARKER Then GoTo Missing
    If Not ExfIsNumber(head(1, 2)) Or Not ExfIsNumber(head(1, 3)) Or Not ExfIsNumber(head(1, 4)) Then GoTo Missing
    mSecTotal = CLng(head(1, 4))
    If mSecTotal < 1 Then GoTo Missing

    toc = ExfBlock(ws, 2, mSecTotal, 4)
    ReDim mSecName(0 To mSecTotal - 1)
    ReDim mSecFirst(0 To mSecTotal - 1)
    ReDim mSecRows(0 To mSecTotal - 1)
    ReDim mSecWidth(0 To mSecTotal - 1)
    For i = 1 To mSecTotal
        mSecName(i - 1) = ExfCellString(toc(i, 1))
        mSecFirst(i - 1) = ExfCellLong(toc(i, 2))
        mSecRows(i - 1) = ExfCellLong(toc(i, 3))
        mSecWidth(i - 1) = ExfCellLong(toc(i, 4))
    Next i

    n = ExfSection(ws, "MSG", block)
    For i = 1 To n
        ExfMessageAdd ExfCellString(block(i, 1)), ExfCellString(block(i, 2))
    Next i

    If CDbl(head(1, 2)) > EXF_PLAN_FORMAT Or CDbl(head(1, 3)) > EXF_MACRO_VERSION Then
        ExfSetError "errPlanTooNew", "needed", ExfCellString(head(1, 3))
        Exit Function
    End If
    p.planFormat = CLng(head(1, 2))

    ' Strings: A = number of chunks, B... = the chunks (Excel cells hold at
    ' most 32,767 characters).
    n = ExfSection(ws, "STR", block)
    ReDim p.strs(0 To n)
    For i = 1 To n
        p.strs(i - 1) = ExfJoinChunks(block, i)
    Next i
    p.strCount = n
    If n = 0 Then GoTo Missing

    p.rootRowsAt = -1               ' plan format 1: every sibling before the rows
    n = ExfSection(ws, "META", block)
    For i = 1 To n
        Select Case ExfCellString(block(i, 1))
            Case "rootName": p.rootName = ExfCellLong(block(i, 2))
            Case "rowTag": p.rowTag = ExfCellLong(block(i, 2))
            Case "multiTag": p.isMultiTag = (ExfCellLong(block(i, 2)) = 1)
            Case "indent": p.indent = ExfCellLong(block(i, 2))
            Case "rootRowsAt": p.rootRowsAt = ExfCellLong(block(i, 2))
            Case "sourceOrder": p.sourceOrder = (ExfCellLong(block(i, 2)) = 1)
            Case "cleanOutput": p.cleanOutput = (ExfCellLong(block(i, 2)) = 1)
            Case "compact": p.compact = (ExfCellLong(block(i, 2)) = 1)
            Case "errorWords": p.errorWords = (ExfCellLong(block(i, 2)) = 1)
            Case "locale": p.locale = ExfCellString(block(i, 2))
            Case "source": p.sourceName = ExfCellString(block(i, 2))
            Case "output": p.outputName = ExfCellString(block(i, 2))
        End Select
    Next i

    n = ExfSection(ws, "PROLOGUE", block)
    p.prologueCount = ExfColumn(block, n, 1, p.prologue)

    n = ExfSection(ws, "ROOTATTR", block)
    p.rootAttrCount = ExfPairs(block, n, p.rootAttrs)

    n = ExfSection(ws, "ROOTLIST", block)
    p.rootListCount = ExfColumn(block, n, 1, p.rootList)

    n = ExfSection(ws, "TYPE", block)
    p.typeCount = ExfColumn(block, n, 1, p.types)
    ExfColumn block, n, 2, p.typeScoped
    ExfColumn block, n, 3, p.typeColStart
    ExfColumn block, n, 4, p.typeColCount

    n = ExfSection(ws, "TYPECOL", block)
    p.typeColTotal = ExfColumn(block, n, 1, p.typeCols)

    n = ExfSection(ws, "TYPEORDER", block)          ' plan format 3; absent before: none
    p.typeOrderCount = ExfColumn(block, n, 1, p.typeOrder)

    n = ExfSection(ws, "NODE", block)
    p.nodeCount = ExfColumn(block, n, 1, p.nodeName)
    ExfColumn block, n, 2, p.nodeText
    ExfColumn block, n, 3, p.nodeSelfClosing
    ExfColumn block, n, 4, p.nodeSlot
    ExfColumn block, n, 5, p.nodeAttrStart
    ExfColumn block, n, 6, p.nodeAttrCount
    ExfColumn block, n, 7, p.nodeChildStart
    ExfColumn block, n, 8, p.nodeChildCount

    n = ExfSection(ws, "NODEATTR", block)
    p.nodeAttrTotal = ExfPairs(block, n, p.nodeAttrs)

    n = ExfSection(ws, "NODECHILD", block)
    p.nodeChildTotal = ExfColumn(block, n, 1, p.nodeChildren)

    n = ExfSection(ws, "WRAP", block)
    p.wrapCount = ExfColumn(block, n, 1, p.wrapName)
    ExfColumn block, n, 2, p.wrapSelfClosing
    ExfColumn block, n, 3, p.wrapListStart
    ExfColumn block, n, 4, p.wrapListCount
    ExfColumn block, n, 5, p.wrapKeyStart
    ExfColumn block, n, 6, p.wrapKeyCount
    ExfColumnOr block, n, 7, p.wrapRowsAt, -1
    ExfColumnOr block, n, 8, p.wrapOptional, 0

    n = ExfSection(ws, "WRAPLIST", block)
    p.wrapListTotal = ExfColumn(block, n, 1, p.wrapLists)

    n = ExfSection(ws, "KEY", block)
    p.keyCount = ExfColumn(block, n, 1, p.keyAttr)
    ExfColumn block, n, 2, p.keyColumn
    ExfColumn block, n, 3, p.keyDefault
    ExfColumnOr block, n, 4, p.keyOptional, 0

    n = ExfSection(ws, "INST", block)
    p.instCount = ExfColumn(block, n, 1, p.instLevel)
    ExfColumn block, n, 2, p.instKey
    ExfColumn block, n, 3, p.instListStart
    ExfColumn block, n, 4, p.instListCount
    ExfColumnOr block, n, 5, p.instRowsAt, -1

    n = ExfSection(ws, "INSTLIST", block)
    p.instListTotal = ExfColumn(block, n, 1, p.instLists)

    n = ExfSection(ws, "COL", block)
    p.colCount = ExfColumn(block, n, 1, p.colName)
    ExfColumn block, n, 2, p.colKind
    ExfColumn block, n, 3, p.colAttr
    ExfColumn block, n, 4, p.colCdata
    ExfColumn block, n, 5, p.colSegStart
    ExfColumn block, n, 6, p.colSegCount

    n = ExfSection(ws, "SEG", block)
    p.segCount = ExfColumn(block, n, 1, p.segName)
    ExfColumn block, n, 2, p.segIndex
    ExfColumn block, n, 3, p.segQualAttr
    ExfColumn block, n, 4, p.segQualValue
    ExfColumnOr block, n, 5, p.segQualStart, -1     ' plan format 3; absent before: none
    ExfColumnOr block, n, 6, p.segQualCount, 0

    n = ExfSection(ws, "SEGQUAL", block)
    p.segQualTotal = ExfPairs(block, n, p.segQuals)

    n = ExfSection(ws, "ANCESTOR", block)
    p.ancestorCount = ExfColumn(block, n, 1, p.ancestorCols)

    ' The value repairs of the site's reconstruction (plan format 3).
    n = ExfSection(ws, "EMPTYATTR", block)
    p.eaCount = ExfColumn(block, n, 1, p.eaCol)
    ExfColumn block, n, 2, p.eaElement
    n = ExfSection(ws, "EAUNDER", block)
    p.eaUnderCount = ExfColumn(block, n, 1, p.eaUnderCol)
    ExfColumn block, n, 2, p.eaUnderElement
    n = ExfSection(ws, "TEXTREQ", block)
    p.trCount = ExfColumn(block, n, 1, p.trCol)
    ExfColumn block, n, 2, p.trElement
    n = ExfSection(ws, "TRUNDER", block)
    p.trUnderCount = ExfColumn(block, n, 1, p.trUnderCol)
    ExfColumn block, n, 2, p.trUnderElement
    n = ExfSection(ws, "KEEPGAP", block)
    p.keepGapCount = ExfColumn(block, n, 1, p.keepGaps)
    n = ExfSection(ws, "ZEROPAD", block)
    p.zeroPadCount = ExfColumn(block, n, 1, p.zeroPadCol)
    ExfColumn block, n, 2, p.zeroPadWidth
    n = ExfSection(ws, "ZEROCODE", block)
    p.zeroCodeCount = ExfColumn(block, n, 1, p.zeroCodeCol)
    ExfColumn block, n, 2, p.zeroCodeHad
    ExfColumnOr block, n, 3, p.zeroCodeStripStart, -1   ' absent: the question of before
    ExfColumnOr block, n, 4, p.zeroCodeStripCount, 0
    n = ExfSection(ws, "ZEROSTRIP", block)
    p.zeroStripTotal = ExfColumn(block, n, 1, p.zeroStrips)
    n = ExfSection(ws, "BOOLSPELL", block)
    p.spellCount = ExfColumn(block, n, 1, p.spellCol)
    ExfColumn block, n, 2, p.spellTrue
    ExfColumn block, n, 3, p.spellFalse
    ExfColumn block, n, 4, p.spellKeepStart
    ExfColumn block, n, 5, p.spellKeepCount
    n = ExfSection(ws, "BOOLKEEP", block)
    p.keepCount = ExfColumn(block, n, 1, p.keepValue)
    ExfColumn block, n, 2, p.keepIsTrueFalse
    ExfColumn block, n, 3, p.keepWord
    n = ExfSection(ws, "SPELLWORD", block)
    p.spellWordCount = ExfPairs(block, n, p.spellWords)

    n = ExfSection(ws, "SELFCLOSE", block)
    p.selfCloseCount = ExfColumn(block, n, 1, p.selfClosing)

    n = ExfSection(ws, "BOOLCOL", block)
    p.boolColCount = ExfColumn(block, n, 1, p.boolCols)

    n = ExfSection(ws, "BOOLTOKEN", block)
    p.boolTokenCount = ExfPairs(block, n, p.boolTokens)

    n = ExfSection(ws, "CASE", block)
    p.caseCount = ExfPairs(block, n, p.caseMap)

    n = ExfSection(ws, "SPACE", block)
    p.spaceCount = ExfColumn(block, n, 1, p.spaces)

    ' Plan format 4 (macro 3.1); absent before: none.
    n = ExfSection(ws, "FIXDEC", block)
    p.fixDecCount = ExfColumn(block, n, 1, p.fixDecCol)
    ExfColumn block, n, 2, p.fixDecDecimals
    ExfColumn block, n, 3, p.fixDecSep
    n = ExfSection(ws, "DECCODE", block)
    p.decCodeCount = ExfColumn(block, n, 1, p.decCodeCol)
    ExfColumn block, n, 2, p.decStripStart
    ExfColumn block, n, 3, p.decStripCount
    n = ExfSection(ws, "DECSTRIP", block)
    p.decStripTotal = ExfColumn(block, n, 1, p.decStrips)
    n = ExfSection(ws, "BARETYPE", block)
    p.bareTypeCount = ExfColumn(block, n, 1, p.bareTypes)
    n = ExfSection(ws, "SCICODE", block)
    p.sciCount = ExfColumn(block, n, 1, p.sciCol)
    ExfColumn block, n, 2, p.sciNumStart
    ExfColumn block, n, 3, p.sciNumCount
    n = ExfSection(ws, "SCINUM", block)
    p.sciNumTotal = ExfColumn(block, n, 1, p.sciNums)
    n = ExfSection(ws, "ERRWORD", block)
    p.errWordCount = ExfColumn(block, n, 1, p.errWords)
    n = ExfSection(ws, "ERRKEEP", block)
    p.errKeepCount = ExfColumn(block, n, 1, p.errKeep)

    ExfReadPlan = True
    Exit Function

Missing:
    ExfSetError "errPlanMissing"
End Function

' Rows of a section as a 1-based block (Empty when the section is empty or
' absent); returns its number of rows.
Private Function ExfSection(ByVal ws As Worksheet, ByVal secName As String, ByRef block As Variant) As Long
    Dim i As Long
    block = Empty
    For i = 0 To mSecTotal - 1
        If mSecName(i) = secName Then
            If mSecRows(i) > 0 And mSecWidth(i) > 0 And mSecFirst(i) > 0 Then
                block = ExfBlock(ws, mSecFirst(i), mSecRows(i), mSecWidth(i))
                ExfSection = mSecRows(i)
            End If
            Exit Function
        End If
    Next i
End Function

' Column col of a block into arr (0-based, one spare slot); returns n.
Private Function ExfColumn(ByRef block As Variant, ByVal n As Long, ByVal col As Long, ByRef arr() As Long) As Long
    Dim r As Long
    ReDim arr(0 To n)
    For r = 1 To n
        arr(r - 1) = ExfCellLong(block(r, col))
    Next r
    ExfColumn = n
End Function

' Like ExfColumn, dflt where the block has no such column (an older plan format).
Private Function ExfColumnOr(ByRef block As Variant, ByVal n As Long, ByVal col As Long, ByRef arr() As Long, ByVal dflt As Long) As Long
    Dim r As Long, wide As Boolean
    ReDim arr(0 To n)
    If n > 0 Then wide = (UBound(block, 2) >= col)
    For r = 1 To n
        If wide Then
            arr(r - 1) = ExfCellLong(block(r, col))
        Else
            arr(r - 1) = dflt
        End If
    Next r
    ExfColumnOr = n
End Function

' Two-column block into a flat pair list (0-based, one spare slot); returns n.
Private Function ExfPairs(ByRef block As Variant, ByVal n As Long, ByRef arr() As Long) As Long
    Dim r As Long
    ReDim arr(0 To 2 * n)
    For r = 1 To n
        arr(2 * r - 2) = ExfCellLong(block(r, 1))
        arr(2 * r - 1) = ExfCellLong(block(r, 2))
    Next r
    ExfPairs = n
End Function

' STR row r: its chunks joined back.
Private Function ExfJoinChunks(ByRef block As Variant, ByVal r As Long) As String
    Dim k As Long, j As Long, parts() As String
    k = ExfCellLong(block(r, 1))
    If k <= 1 Then
        If k = 1 Then ExfJoinChunks = ExfCellString(block(r, 2))
        Exit Function
    End If
    ReDim parts(0 To k - 1)
    For j = 1 To k
        parts(j - 1) = ExfCellString(block(r, 1 + j))
    Next j
    ExfJoinChunks = Join(parts, vbNullString)
End Function

Public Function ExfCellString(ByRef v As Variant) As String
    If VarType(v) = vbString Then
        ExfCellString = v
    ElseIf IsEmpty(v) Or IsError(v) Then
        ExfCellString = vbNullString
    Else
        ExfCellString = CStr(v)
    End If
End Function

Private Function ExfCellLong(ByRef v As Variant) As Long
    If ExfIsNumber(v) Then ExfCellLong = CLng(v)
End Function

Private Function ExfIsNumber(ByRef v As Variant) As Boolean
    Select Case VarType(v)
        Case vbDouble, vbLong, vbInteger, vbSingle, vbCurrency, vbDecimal, vbByte
            ExfIsNumber = True
    End Select
End Function
modExfRun.basOne generation from start to finish: reading, rebuilding, any questions, save dialog, writing the file, final message281 lines
Attribute VB_Name = "modExfRun"
' ExcelifyXML - one run of the macro on a workbook: plan, Data sheet, engine,
' save dialog, file, message. Called by the button (modExfEntry) on the
' workbook that holds this code.
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary
Option Private Module

' Returns a report: "OK<TAB>rows<TAB>bytes<TAB>conversions<TAB>cells<TAB>new
' columns<TAB>ignored columns<TAB>zeros put back<TAB>milliseconds", or
' "ERR<TAB>key<TAB>name=value...".
' Not interactive (the test benches only, from inside the project): no dialog
' and no message, writes outPath; acceptStops answers Yes to the questions
' (else a question is the report).
Public Function ExfRunBook(ByVal book As Workbook, ByVal outPath As String, ByVal interactive As Boolean, _
                           Optional ByVal acceptStops As Boolean = False) As String
    Dim p As ExfPlan, sh As ExfSheet, wsPlan As Worksheet, wsData As Worksheet
    Dim target As String, extensionFixed As Boolean, fileNo As Integer, bytes As Double
    Dim t0 As Double, cancelKey As Long, report As String, msg As String, warn As Boolean, inPlace As Boolean

    On Error GoTo Failed
    t0 = Timer
    cancelKey = Application.EnableCancelKey
    Application.EnableCancelKey = xlErrorHandler     ' Esc stops cleanly
    ExfClearError
    ExfMessagesClear

    ' 1. The plan
    Set wsPlan = ExfSheetByCodeName(book, "shPlan")
    If wsPlan Is Nothing Then
        ExfSetError "errPlanMissing"
        GoTo Finish
    End If
    If Not ExfReadPlan(wsPlan, p) Then GoTo Finish

    ' 2. The Data sheet
    Set wsData = ExfSheetByCodeName(book, "shData")
    If wsData Is Nothing Then
        ExfSetError "errDataSheetMissing"
        GoTo Finish
    End If
    If Not ExfReadHeaders(wsData, sh) Then GoTo Finish
    If Not ExfEngineStart(p, sh.headers, sh.nCols) Then GoTo Finish
    If interactive Then
        If wsData.FilterMode Then
            If MsgBox(ExfFill(ExfMessageText("filterNotice"), "sheet", wsData.Name), _
                      vbOKCancel + vbQuestion, ExfMessageText("title")) <> vbOK Then GoTo Finish
        End If
    End If
    ExfStatus ExfFill(ExfMessageText("progressReading"), "done", "0", "total", CStr(sh.lastRow - sh.firstRow + 1))
    If Not ExfReadRows(wsData, sh) Then GoTo Finish

    ' 3. The XML, built in memory (every refusal happens here, before any file).
    ' Values changed that can't be put back (leading zeros, decimal zeros,
    ' codes like 12E3, error words) are asked about first, as the site stops
    ' first.
    If Not ExfEngineCheckColumns() Then GoTo Finish
    ExfEngineFindChanges p
    If Not ExfRunAsk(ExfEngineAskChangesKey(), ExfEngineAskChanges(), interactive, acceptStops) Then GoTo Finish
    If Not ExfEngineBuild(p) Then GoTo Finish
    ' The site's stops, as questions: Yes is its "Reconstruire quand meme".
    If Not ExfRunAsk(ExfEngineAskIgnoredKey(), ExfEngineAskIgnored(), interactive, acceptStops) Then GoTo Finish
    If Not ExfRunAsk("askInvalidCharacters", ExfEngineAskInvalid(), interactive, acceptStops) Then GoTo Finish

    ' 4. Where to write
    If interactive Then
        target = ExfAskSavePath(book.Path, p.outputName, extensionFixed)
        If Len(target) = 0 Then GoTo Finish         ' cancelled
    Else
        ' A new .xml file only: never another kind, never over an existing file.
        target = outPath
        If LCase$(Right$(target, 4)) <> ".xml" Or ExfFileExists(target) Then
            ExfSetError "errWrite", "path", target
            GoTo Finish
        End If
    End If
    If ExfIsCloudPath(target) Then
        ExfSetError "errCloudPath", "path", target
        GoTo Finish
    End If
    If Not ExfPathEncodable(target) Then
        ExfSetError "errPathCharacters", "path", target
        GoTo Finish
    End If
    If interactive Then
        ' Windows: this dialog doesn't warn about an existing file. Mac: the
        ' dialog itself asked, for the very name it returned.
        If ExfOverwriteNeedsConfirm(target, extensionFixed) Then
            If MsgBox(ExfFill(ExfMessageText("confirmOverwrite"), "name", ExfFileName(target)), _
                      vbYesNo + vbQuestion + vbDefaultButton2, ExfMessageText("title")) <> vbYes Then GoTo Finish
        End If
    End If

    ' Mac, file chosen in the save dialog: the only file Excel may write, so it
    ' is written in place. Elsewhere (Windows, test benches): next to it, then
    ' renamed over it.
#If Mac Then
    inPlace = interactive
#End If
    ExfStatus ExfMessageText("progressWriting")
    fileNo = ExfOpenOutput(target, inPlace)
    If fileNo = 0 Then GoTo Finish
    bytes = ExfWriteXml(p, fileNo)
    If inPlace Then
        Close #fileNo
    ElseIf Not ExfCommitOutput(fileNo, target) Then
        fileNo = 0
        GoTo Finish
    End If
    fileNo = 0

    report = "OK" & vbTab & ExfEngineRowCount() & vbTab & bytes & vbTab & sh.conversions & vbTab & _
        ExfJoinCells(sh, ",") & vbTab & ExfEngineNewColumns() & vbTab & ExfEngineIgnoredColumns() & vbTab & _
        ExfEnginePadded() & vbTab & Round((Timer - t0) * 1000)
    If interactive Then
        ExfStatusClear
        msg = ExfFill(ExfMessageText("success"), "rows", CStr(ExfEngineRowCount()), "path", target)
        If sh.conversions > 0 Then
            msg = msg & vbLf & vbLf & ExfFill(ExfMessageText("successConversions"), _
                "count", CStr(sh.conversions), "cells", ExfJoinCells(sh, ", "))
            warn = True
        End If
        If Len(ExfEngineNewColumns()) > 0 Then
            msg = msg & vbLf & vbLf & ExfFill(ExfMessageText("successNewColumns"), "columns", ExfShortList(ExfEngineNewColumns()))
            warn = True
        End If
        If Len(ExfEngineIgnoredColumns()) > 0 Then
            msg = msg & vbLf & vbLf & ExfFill(ExfMessageText("successIgnoredColumns"), "columns", ExfShortList(ExfEngineIgnoredColumns()))
            warn = True
        End If
        If Len(ExfEnginePadded()) > 0 Then
            msg = msg & vbLf & vbLf & ExfFill(ExfMessageText("successPaddedZeros"), "columns", ExfPaddedList(ExfEnginePadded()))
            warn = True
        End If
        If warn Then
            MsgBox msg, vbExclamation, ExfMessageText("title")
        Else
            MsgBox msg, vbInformation, ExfMessageText("title")
        End If
    End If

Finish:
    On Error Resume Next
    If fileNo <> 0 Then ExfAbandonOutput fileNo, target, inPlace
    ExfEngineReset
    ExfStatusClear
    Application.EnableCancelKey = cancelKey
    If Len(ExfErrorKey()) > 0 Then
        report = ExfErrorReport()
        If interactive Then MsgBox ExfErrorMessage(), vbExclamation, ExfMessageText("title")
    ElseIf Len(report) = 0 Then
        report = "CANCELLED"
    End If
    ExfRunBook = report
    Exit Function

Failed:
    If Err.Number = 18 Then                   ' Esc: stopped by the user, nothing to say
        report = "CANCELLED"
    Else
        ExfSetError "errUnexpected", "code", CStr(Err.Number), "description", Err.Description
    End If
    Resume Finish
End Function

' A question of the engine ("" lst: none). Yes goes on; No stops without a
' word (the question said it all). Test benches: acceptStops goes on, else the
' question becomes the report.
Private Function ExfRunAsk(ByVal key As String, ByVal lst As String, ByVal interactive As Boolean, ByVal acceptStops As Boolean) As Boolean
    If Len(lst) = 0 Or acceptStops Then
        ExfRunAsk = True
    ElseIf interactive Then
        ExfStatusClear
        ExfRunAsk = (MsgBox(ExfFill(ExfMessageText(key), "list", lst), vbYesNo + vbExclamation + vbDefaultButton2, _
                     ExfMessageText("title")) = vbYes)
    Else
        ExfSetError key, "list", lst
    End If
End Function

' Normally the file is written next to its final place, then renamed over it:
' an existing file is only replaced once the new one is complete. In place on
' Mac for the file chosen in the save dialog, the only one the sandbox lets
' Excel write there (see ExfAskSavePath).
Private Function ExfOpenOutput(ByVal target As String, ByVal inPlace As Boolean) As Integer
    On Error GoTo Denied
    If inPlace Then
        ExfOpenOutput = ExfWriterOpenInPlace(target)
    Else
        ExfOpenOutput = ExfWriterOpen(target)
    End If
    Exit Function
Denied:
#If Mac Then
    ExfSetError "errMacAccess", "path", target
#Else
    ExfSetError "errWrite", "path", target
#End If
End Function

Private Function ExfCommitOutput(ByVal fileNo As Integer, ByVal target As String) As Boolean
    On Error GoTo Denied
    ExfWriterCommit fileNo, target
    ExfCommitOutput = True
    Exit Function
Denied:
    ' The complete temporary file (target & ".tmp") is left in place.
    ExfSetError "errWrite", "path", target
    ExfCloseQuietly fileNo
End Function

' A run stopped while writing leaves no half-written file behind.
Private Sub ExfAbandonOutput(ByVal fileNo As Integer, ByVal target As String, ByVal inPlace As Boolean)
    On Error Resume Next
    Close #fileNo
    If inPlace Then
        Kill target
    Else
        Kill target & ".tmp"
    End If
End Sub

Private Sub ExfCloseQuietly(ByVal fileNo As Integer)
    On Error Resume Next
    Close #fileNo
End Sub

Private Function ExfOverwriteNeedsConfirm(ByVal target As String, ByVal extensionFixed As Boolean) As Boolean
#If Mac Then
    Exit Function
#End If
    ExfOverwriteNeedsConfirm = ExfFileExists(target)
End Function

' The first converted cells (at most five), e.g. "B7, C12".
Private Function ExfJoinCells(ByRef sh As ExfSheet, ByVal separator As String) As String
    Dim i As Long, s As String
    For i = 0 To 4
        If Len(sh.convCells(i)) > 0 Then
            If Len(s) > 0 Then s = s & separator
            s = s & sh.convCells(i)
        End If
    Next i
    ExfJoinCells = s
End Function

' = report.ts paddedList: "column=cells,..." as "ean (12), zip (3)", the
' first 8 then ", ..." - names cut at 60 characters, as ExfShortList.
Private Function ExfPaddedList(ByVal list As String) As String
    Dim items() As String, i As Long, s As String, eq As Long, nm As String
    items = Split(list, ",")
    For i = 0 To UBound(items)
        If i = 8 Then
            s = s & ", " & ChrW(8230)
            Exit For
        End If
        If i > 0 Then s = s & ", "
        eq = InStrRev(items(i), "=")
        nm = Left$(items(i), eq - 1)
        If Len(nm) > 60 Then nm = Left$(nm, 60) & ChrW(8230)
        s = s & nm & " (" & Mid$(items(i), eq + 1) & ")"
    Next i
    ExfPaddedList = s
End Function

' A comma-separated list shortened for a message box (about 1,000 characters).
Private Function ExfShortList(ByVal list As String) As String
    Dim items() As String, i As Long, s As String
    items = Split(list, ",")
    For i = 0 To UBound(items)
        If i = 8 Then
            s = s & ", " & ChrW(8230)
            Exit For
        End If
        If i > 0 Then s = s & ", "
        If Len(items(i)) > 60 Then s = s & Left$(items(i), 60) & ChrW(8230) Else s = s & items(i)
    Next i
    ExfShortList = s
End Function
modExfTree.basRebuilding the XML (3/4): the element tree, where each value finds its tag621 lines
Attribute VB_Name = "modExfTree"
' ExcelifyXML - the reconstruction engine, part 3: the element tree, where
' each row's values find their element. Port of class Tree, layOut and
' applyColumn in src/lib/excel-macro/engine/execute.ts. Element and attribute names are held
' as numbers (their place in the plan's string pool), which compares faster
' than text in VBA; two names are equal exactly when their numbers are.
' The engine is split in four modules: modExfEngine, modExfBuild, this one,
' modExfWrite.
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary
Option Private Module

' The tree (execute.ts class Tree): one entry per element, attributes chained.
' Public: read by modExfWrite, which writes it out.
Private mNodeCount As Long
Public nNameId() As Long
Public nText() As String
Public nCdata() As Boolean
Public nSelf() As Boolean
Public nStatic() As Long               ' plan node emitted as is, else -1
Public nFirst() As Long
Private nLast() As Long
Public nNext() As Long
Public nAttrFirst() As Long
Private nAttrLast() As Long
Public nRemoved() As Boolean
Private nFilled() As Boolean
Private mAttrCount As Long
Public aKeyId() As Long
Public aVal() As String
Public aNext() As Long
Private mRoot As Long
Private mWrapperIndex As ExfStrMap      ' wrappers and slots by parent, name and attributes
Private mSlots() As Long
Private mSlotCount As Long
Private mStrIndex As ExfStrMap          ' the plan's strings, for the names of new columns
Private mExtraNames() As String         ' names of new columns absent from the string pool
Private mExtraCount As Long
Private mKeepGaps As ExfStrMap          ' lists whose empty occurrences are written (KEEPGAP)
Private mHasKeepGaps As Boolean

' ============================================================================
' Tree primitives
' ============================================================================

Public Sub ExfTreeInit(ByRef p As ExfPlan, ByVal rows As Long)
    Dim cap As Long, i As Long
    cap = 1024
    Do While cap < rows * 4 And cap < 4194304
        cap = cap * 2
    Loop
    mNodeCount = 0
    ReDim nNameId(0 To cap - 1)
    ReDim nText(0 To cap - 1)
    ReDim nCdata(0 To cap - 1)
    ReDim nSelf(0 To cap - 1)
    ReDim nStatic(0 To cap - 1)
    ReDim nFirst(0 To cap - 1)
    ReDim nLast(0 To cap - 1)
    ReDim nNext(0 To cap - 1)
    ReDim nAttrFirst(0 To cap - 1)
    ReDim nAttrLast(0 To cap - 1)
    ReDim nRemoved(0 To cap - 1)
    ReDim nFilled(0 To cap - 1)
    mAttrCount = 0
    ReDim aKeyId(0 To 1023)
    ReDim aVal(0 To 1023)
    ReDim aNext(0 To 1023)
    mSlotCount = 0
    ReDim mSlots(0 To 15)
    ExfMapInit mWrapperIndex, 64
    ExfMapInit mStrIndex, p.strCount
    For i = 0 To p.strCount - 1
        ExfMapSet mStrIndex, p.strs(i), i
    Next i
    mExtraCount = 0
    ReDim mExtraNames(0 To 15)
    mRoot = 0
    ExfMapInit mKeepGaps, p.keepGapCount
    For i = 0 To p.keepGapCount - 1
        ExfMapSet mKeepGaps, p.strs(p.keepGaps(i)), 1
    Next i
    mHasKeepGaps = (p.keepGapCount > 0)
End Sub

Private Sub ExfGrowNodes()
    Dim cap As Long
    cap = 2 * (UBound(nNameId) + 1)
    ReDim Preserve nNameId(0 To cap - 1)
    ReDim Preserve nText(0 To cap - 1)
    ReDim Preserve nCdata(0 To cap - 1)
    ReDim Preserve nSelf(0 To cap - 1)
    ReDim Preserve nStatic(0 To cap - 1)
    ReDim Preserve nFirst(0 To cap - 1)
    ReDim Preserve nLast(0 To cap - 1)
    ReDim Preserve nNext(0 To cap - 1)
    ReDim Preserve nAttrFirst(0 To cap - 1)
    ReDim Preserve nAttrLast(0 To cap - 1)
    ReDim Preserve nRemoved(0 To cap - 1)
    ReDim Preserve nFilled(0 To cap - 1)
End Sub

' = Tree.newNode
Public Function ExfTreeNewNode(ByVal nameId As Long, ByVal selfClosing As Boolean, ByVal staticId As Long) As Long
    Dim id As Long
    id = mNodeCount
    If id > UBound(nNameId) Then ExfGrowNodes
    nNameId(id) = nameId
    nSelf(id) = selfClosing
    nStatic(id) = staticId
    nFirst(id) = -1
    nLast(id) = -1
    nNext(id) = -1
    nAttrFirst(id) = -1
    nAttrLast(id) = -1
    mNodeCount = id + 1
    ExfTreeNewNode = id
End Function

' = Tree.append
Public Sub ExfTreeAppend(ByVal parentNode As Long, ByVal child As Long)
    If nLast(parentNode) < 0 Then
        nFirst(parentNode) = child
    Else
        nNext(nLast(parentNode)) = child
    End If
    nLast(parentNode) = child
End Sub

' = Tree.setAttr: an existing attribute keeps its place, as in a JavaScript object.
Public Sub ExfTreeSetAttr(ByVal node As Long, ByVal keyId As Long, ByRef aValue As String)
    Dim a As Long, cap As Long
    a = nAttrFirst(node)
    Do While a >= 0
        If aKeyId(a) = keyId Then
            aVal(a) = aValue
            Exit Sub
        End If
        a = aNext(a)
    Loop
    a = mAttrCount
    If a > UBound(aKeyId) Then
        cap = 2 * (UBound(aKeyId) + 1)
        ReDim Preserve aKeyId(0 To cap - 1)
        ReDim Preserve aVal(0 To cap - 1)
        ReDim Preserve aNext(0 To cap - 1)
    End If
    aKeyId(a) = keyId
    aVal(a) = aValue
    aNext(a) = -1
    If nAttrLast(node) < 0 Then
        nAttrFirst(node) = a
    Else
        aNext(nAttrLast(node)) = a
    End If
    nAttrLast(node) = a
    mAttrCount = a + 1
End Sub

' = Tree.getAttr: False when absent.
Private Function ExfGetAttr(ByVal node As Long, ByVal keyId As Long, ByRef aValue As String) As Boolean
    Dim a As Long
    a = nAttrFirst(node)
    Do While a >= 0
        If aKeyId(a) = keyId Then
            aValue = aVal(a)
            ExfGetAttr = True
            Exit Function
        End If
        a = aNext(a)
    Loop
End Function

Public Sub ExfTreeSetText(ByVal node As Long, ByRef aValue As String)
    nText(node) = aValue
End Sub

Public Sub ExfTreeSetRoot(ByVal node As Long)
    mRoot = node
End Sub

' First visit of a wrapper instance (its siblings are laid out once).
Public Function ExfTreeFilled(ByVal node As Long) As Boolean
    ExfTreeFilled = nFilled(node)
End Function

Public Sub ExfTreeMarkFilled(ByVal node As Long)
    nFilled(node) = True
End Sub

' Wrapper elements (and slots) by "parent|name|attribute signature", -1 when absent.
Public Function ExfTreeWrapperGet(ByRef key As String) As Long
    ExfTreeWrapperGet = ExfMapGet(mWrapperIndex, key)
End Function

Public Sub ExfTreeWrapperSet(ByRef key As String, ByVal node As Long)
    ExfMapSet mWrapperIndex, key, node
End Sub

' Name of a new column as a number: its place in the string pool when the pool
' has it (the same name as a path segment is the same element), else a number
' past the pool.
Public Function ExfTreeNameIdOf(ByRef p As ExfPlan, ByRef nm As String) As Long
    Dim id As Long
    id = ExfMapGet(mStrIndex, nm)
    If id < 0 Then
        If mExtraCount > UBound(mExtraNames) Then ReDim Preserve mExtraNames(0 To 2 * mExtraCount)
        mExtraNames(mExtraCount) = nm
        id = p.strCount + mExtraCount
        mExtraCount = mExtraCount + 1
    End If
    ExfTreeNameIdOf = id
End Function

Public Function ExfTreeNameText(ByRef p As ExfPlan, ByVal nameId As Long) As String
    If nameId < p.strCount Then
        ExfTreeNameText = p.strs(nameId)
    Else
        ExfTreeNameText = mExtraNames(nameId - p.strCount)
    End If
End Function

Public Function ExfTreeRoot() As Long
    ExfTreeRoot = mRoot
End Function

' A slot no row reached is left out.
Public Sub ExfTreePruneSlots()
    Dim i As Long
    For i = 0 To mSlotCount - 1
        If Not nFilled(mSlots(i)) Then nRemoved(mSlots(i)) = True
    Next i
End Sub

' ============================================================================
' Layout and columns
' ============================================================================

' = execute.ts layOut: kept siblings (emitted from the plan as they are), and
' slots re-created empty, where the rows' container sits among them. level:
' the wrapper level whose rows look among the parent's children (-1: none,
' the siblings laid out after every row).
Public Sub ExfTreeLayOut(ByRef p As ExfPlan, ByVal parentNode As Long, ByRef list() As Long, ByVal start As Long, ByVal count As Long, _
                         ByVal level As Long)
    Dim j As Long, id As Long, el As Long, a As Long, na As Long, first As Long, okey As String
    Dim keys() As String, vals() As String
    For j = start To start + count - 1
        id = list(j)
        If p.nodeSlot(id) = 1 Then
            el = ExfTreeNewNode(p.nodeName(id), False, -1)
            na = p.nodeAttrCount(id)
            first = p.nodeAttrStart(id)
            If na > 0 Then
                ReDim keys(0 To na - 1)
                ReDim vals(0 To na - 1)
            End If
            For a = first To first + na - 1
                keys(a - first) = p.strs(p.nodeAttrs(2 * a))
                vals(a - first) = p.strs(p.nodeAttrs(2 * a + 1))
                ExfTreeSetAttr el, p.nodeAttrs(2 * a), p.strs(p.nodeAttrs(2 * a + 1))
            Next a
            ExfTreeAppend parentNode, el
            ExfAddSlotKey parentNode & "|" & p.strs(p.nodeName(id)) & "|" & ExfAttrSig(keys, vals, na), el
            ' A level whose rows find their container by the values it was keyed
            ' with: the slot by its own.
            If level >= 0 And level < p.wrapCount Then
                If p.wrapOptional(level) = 1 And p.nodeName(id) = p.wrapName(level) Then
                    okey = ExfTreeOptionalKey(p, level, id)
                    If Len(okey) > 0 Then
                        okey = parentNode & "|" & p.strs(p.nodeName(id)) & "|" & okey
                        If ExfMapGet(mWrapperIndex, okey) < 0 Then ExfMapSet mWrapperIndex, okey, el
                    End If
                End If
            End If
        Else
            ExfTreeAppend parentNode, ExfTreeNewNode(p.nodeName(id), False, id)
        End If
    Next j
End Sub

' = execute.ts optionalKey (value-repairs.ts ContextRepairs.sameInstance): how
' the rows of the level name the slot (plan node id) when some container of
' the level lacked an attribute - "o|" then the values of the attributes the
' rows are keyed with, "" for one the slot lacks; "" when the slot has an
' attribute that is not the level's, which no row matches.
Private Function ExfTreeOptionalKey(ByRef p As ExfPlan, ByVal level As Long, ByVal id As Long) As String
    Dim a As Long, k As Long, known As Boolean, v As String, s As String
    For a = p.nodeAttrStart(id) To p.nodeAttrStart(id) + p.nodeAttrCount(id) - 1
        known = False
        For k = p.wrapKeyStart(level) To p.wrapKeyStart(level) + p.wrapKeyCount(level) - 1
            If p.keyAttr(k) = p.nodeAttrs(2 * a) Then
                known = True
                Exit For
            End If
        Next k
        If Not known Then Exit Function
    Next a
    s = "o|"
    For k = p.wrapKeyStart(level) To p.wrapKeyStart(level) + p.wrapKeyCount(level) - 1
        If p.keyColumn(k) >= 0 Then
            v = vbNullString
            For a = p.nodeAttrStart(id) To p.nodeAttrStart(id) + p.nodeAttrCount(id) - 1
                If p.nodeAttrs(2 * a) = p.keyAttr(k) Then v = p.strs(p.nodeAttrs(2 * a + 1))
            Next a
            s = s & ExfLenKey(v)
        End If
    Next k
    ExfTreeOptionalKey = s
End Function

Private Sub ExfAddSlotKey(ByVal key As String, ByVal el As Long)
    If ExfMapGet(mWrapperIndex, key) < 0 Then ExfMapSet mWrapperIndex, key, el
    If mSlotCount > UBound(mSlots) Then ReDim Preserve mSlots(0 To 2 * mSlotCount)
    mSlots(mSlotCount) = el
    mSlotCount = mSlotCount + 1
End Sub

' = execute.ts applyColumn (reconstruct.ts applyDescriptor + descendPath).
' A list in one cell (EXF_COL_LIST, plan format 5): one element per non-empty
' line, in order, appended to the element the other segments reach - found or
' created as for any column; nothing at all, not even that element, when no
' line is left. attrOverride: a renamed attribute's new name (macro 3.3), as a
' name id written in place of the column's own; -1 for that one.
Public Sub ExfTreeApplyColumn(ByRef p As ExfPlan, ByRef isSelf() As Boolean, ByVal rowNode As Long, ByVal colId As Long, ByRef aValue As String, ByVal attrOverride As Long)
    Dim kind As Long, cur As Long, s As Long, nameId As Long, idx As Long, cnt As Long
    Dim found As Long, c As Long, fresh As Long, attrId As Long, want As String, got As String
    Dim q As Long, qFirst As Long, qLast As Long, qualOk As Boolean
    Dim segLast As Long, listVals() As String, nVals As Long, i As Long

    kind = p.colKind(colId)
    If kind = EXF_COL_NONE Then Exit Sub
    segLast = p.colSegStart(colId) + p.colSegCount(colId) - 1
    If kind = EXF_COL_LIST Then
        nVals = ExfListLines(aValue, listVals)
        If nVals = 0 Then Exit Sub
        segLast = segLast - 1
    End If
    cur = rowNode
    For s = p.colSegStart(colId) To segLast
        nameId = p.segName(s)
        If p.segIndex(s) >= 0 Then
            ' Positional: materialize the same-name children up to the index.
            idx = p.segIndex(s)
            cnt = 0
            found = -1
            c = nFirst(cur)
            Do While c >= 0
                If nNameId(c) = nameId Then
                    If cnt = idx Then found = c
                    cnt = cnt + 1
                End If
                c = nNext(c)
            Loop
            Do While found < 0
                fresh = ExfTreeNewNode(nameId, isSelf(nameId), -1)
                ExfTreeAppend cur, fresh
                If cnt = idx Then found = fresh
                cnt = cnt + 1
            Loop
        ElseIf p.segQualStart(s) >= 0 Then
            ' Several attributes together (attribute-id + xml:lang...): each
            ' must match, an absent one (-1) included - seo_url without xml:lang
            ' is not seo_url in fr-FR. Created with the present ones, in order.
            qFirst = p.segQualStart(s)
            qLast = qFirst + p.segQualCount(s) - 1
            found = -1
            c = nFirst(cur)
            Do While c >= 0
                If nNameId(c) = nameId Then
                    qualOk = True
                    For q = qFirst To qLast
                        If p.segQuals(2 * q + 1) < 0 Then
                            If ExfGetAttr(c, p.segQuals(2 * q), got) Then qualOk = False
                        ElseIf ExfGetAttr(c, p.segQuals(2 * q), got) Then
                            If got <> p.strs(p.segQuals(2 * q + 1)) Then qualOk = False
                        Else
                            qualOk = False
                        End If
                        If Not qualOk Then Exit For
                    Next q
                    If qualOk Then
                        found = c
                        Exit Do
                    End If
                End If
                c = nNext(c)
            Loop
            If found < 0 Then
                found = ExfTreeNewNode(nameId, isSelf(nameId), -1)
                For q = qFirst To qLast
                    If p.segQuals(2 * q + 1) >= 0 Then ExfTreeSetAttr found, p.segQuals(2 * q), p.strs(p.segQuals(2 * q + 1))
                Next q
                ExfTreeAppend cur, found
            End If
        ElseIf p.segQualAttr(s) >= 0 Then
            attrId = p.segQualAttr(s)
            want = p.strs(p.segQualValue(s))
            found = -1
            c = nFirst(cur)
            Do While c >= 0
                If nNameId(c) = nameId Then
                    If ExfGetAttr(c, attrId, got) Then
                        If got = want Then
                            found = c
                            Exit Do
                        End If
                    End If
                End If
                c = nNext(c)
            Loop
            If found < 0 Then
                found = ExfTreeNewNode(nameId, isSelf(nameId), -1)
                ExfTreeSetAttr found, attrId, want
                ExfTreeAppend cur, found
            End If
        Else
            found = -1
            c = nFirst(cur)
            Do While c >= 0
                If nNameId(c) = nameId Then
                    found = c
                    Exit Do
                End If
                c = nNext(c)
            Loop
            If found < 0 Then
                found = ExfTreeNewNode(nameId, isSelf(nameId), -1)
                ExfTreeAppend cur, found
            End If
        End If
        cur = found
    Next s
    If kind = EXF_COL_TEXT Then
        nText(cur) = aValue
        If p.colCdata(colId) = 1 Then nCdata(cur) = True
    ElseIf kind = EXF_COL_ATTR Then
        If attrOverride >= 0 Then
            ExfTreeSetAttr cur, attrOverride, aValue
        Else
            ExfTreeSetAttr cur, p.colAttr(colId), aValue
        End If
    ElseIf kind = EXF_COL_LIST Then
        nameId = p.segName(segLast + 1)
        For i = 0 To nVals - 1
            fresh = ExfTreeNewNode(nameId, isSelf(nameId), -1)
            nText(fresh) = listVals(i)
            ExfTreeAppend cur, fresh
        Next i
    End If
End Sub

' = text.ts listLines (list-columns.ts listValuesOf): the lines of a list
' cell, split on CR LF, a lone CR or LF - Excel holds Chr(10) for a line typed
' with Alt+Enter, a pasted cell may hold CR LF or CR - empty lines dropped,
' the others in order, as they are. Returns how many (listVals() is 0-based).
Private Function ExfListLines(ByRef aValue As String, ByRef listVals() As String) As Long
    Dim parts() As String, i As Long, n As Long
    parts = Split(Replace(Replace(aValue, vbCrLf, vbLf), vbCr, vbLf), vbLf)
    ReDim listVals(0 To UBound(parts) + 1)
    For i = 0 To UBound(parts)
        If Len(parts(i)) > 0 Then
            listVals(n) = parts(i)
            n = n + 1
        End If
    Next i
    ExfListLines = n
End Function

' = execute.ts findAt (value-repairs.ts findAt): the element at a column's
' path under the row, found as ExfTreeApplyColumn finds it - never created;
' -1 when absent.
Public Function ExfTreeFindAt(ByRef p As ExfPlan, ByVal rowNode As Long, ByVal colId As Long) As Long
    Dim cur As Long, s As Long, nameId As Long, idx As Long, cnt As Long, found As Long, c As Long
    Dim q As Long, qFirst As Long, qLast As Long, qualOk As Boolean, got As String, attrId As Long, want As String

    ExfTreeFindAt = -1
    If p.colSegCount(colId) = 0 Then Exit Function
    cur = rowNode
    For s = p.colSegStart(colId) To p.colSegStart(colId) + p.colSegCount(colId) - 1
        nameId = p.segName(s)
        found = -1
        If p.segIndex(s) >= 0 Then
            idx = p.segIndex(s)
            cnt = 0
            c = nFirst(cur)
            Do While c >= 0
                If nNameId(c) = nameId Then
                    If cnt = idx Then
                        found = c
                        Exit Do
                    End If
                    cnt = cnt + 1
                End If
                c = nNext(c)
            Loop
        ElseIf p.segQualStart(s) >= 0 Then
            qFirst = p.segQualStart(s)
            qLast = qFirst + p.segQualCount(s) - 1
            c = nFirst(cur)
            Do While c >= 0
                If nNameId(c) = nameId Then
                    qualOk = True
                    For q = qFirst To qLast
                        If p.segQuals(2 * q + 1) < 0 Then
                            If ExfGetAttr(c, p.segQuals(2 * q), got) Then qualOk = False
                        ElseIf ExfGetAttr(c, p.segQuals(2 * q), got) Then
                            If got <> p.strs(p.segQuals(2 * q + 1)) Then qualOk = False
                        Else
                            qualOk = False
                        End If
                        If Not qualOk Then Exit For
                    Next q
                    If qualOk Then
                        found = c
                        Exit Do
                    End If
                End If
                c = nNext(c)
            Loop
        ElseIf p.segQualAttr(s) >= 0 Then
            attrId = p.segQualAttr(s)
            want = p.strs(p.segQualValue(s))
            c = nFirst(cur)
            Do While c >= 0
                If nNameId(c) = nameId Then
                    If ExfGetAttr(c, attrId, got) Then
                        If got = want Then
                            found = c
                            Exit Do
                        End If
                    End If
                End If
                c = nNext(c)
            Loop
        Else
            c = nFirst(cur)
            Do While c >= 0
                If nNameId(c) = nameId Then
                    found = c
                    Exit Do
                End If
                c = nNext(c)
            Loop
        End If
        If found < 0 Then Exit Function
        cur = found
    Next s
    ExfTreeFindAt = cur
End Function

' No child and no text (execute.ts tidyRow): a removal has not happened yet.
Public Function ExfTreeIsBare(ByVal node As Long) As Boolean
    ExfTreeIsBare = (nFirst(node) < 0 And Len(nText(node)) = 0)
End Function

Public Sub ExfTreeRemove(ByVal node As Long)
    nRemoved(node) = True
End Sub

' = execute.ts prune (value-repairs.ts pruneEmpty): the elements below node
' left with no text, no attribute and no child, removed, deepest first -
' except in the lists named in KEEPGAP, by their element names from the row
' joined by "." (trail: the node's; computed only when KEEPGAP has any).
Public Sub ExfTreePrune(ByRef p As ExfPlan, ByVal node As Long, ByVal trail As String, ByVal depth As Long)
    Dim c As Long, d As Long, kids As Boolean, own As String
    If depth > 200 Then Exit Sub                ' MAX_PATH_DEPTH, as the site
    c = nFirst(node)
    Do While c >= 0
        If Not nRemoved(c) Then ExfTreePrune p, c, ExfTreeTrail(p, trail, c), depth + 1
        c = nNext(c)
    Loop
    c = nFirst(node)
    Do While c >= 0
        If Not nRemoved(c) And nAttrFirst(c) < 0 And Len(nText(c)) = 0 Then
            kids = False
            d = nFirst(c)
            Do While d >= 0
                If Not nRemoved(d) Then
                    kids = True
                    Exit Do
                End If
                d = nNext(d)
            Loop
            If Not kids Then
                If mHasKeepGaps Then
                    own = ExfTreeTrail(p, trail, c)
                    If ExfMapGet(mKeepGaps, own) < 0 Then nRemoved(c) = True
                Else
                    nRemoved(c) = True
                End If
            End If
        End If
        c = nNext(c)
    Loop
End Sub

' A child's trail: its parent's, then its own name ("images.image-group").
Private Function ExfTreeTrail(ByRef p As ExfPlan, ByRef trail As String, ByVal c As Long) As String
    If Not mHasKeepGaps Then Exit Function
    If Len(trail) = 0 Then
        ExfTreeTrail = ExfTreeNameText(p, nNameId(c))
    Else
        ExfTreeTrail = trail & "." & ExfTreeNameText(p, nNameId(c))
    End If
End Function

' Frees the tree's memory.
Public Sub ExfTreeReset()
    mNodeCount = 0
    mAttrCount = 0
    mSlotCount = 0
    mExtraCount = 0
    Erase nNameId, nText, nCdata, nSelf, nStatic, nFirst, nLast, nNext, nAttrFirst, nAttrLast, nRemoved, nFilled
    Erase aKeyId, aVal, aNext, mSlots, mExtraNames
    ExfMapInit mWrapperIndex, 16
    ExfMapInit mStrIndex, 16
    ExfMapInit mKeepGaps, 16
    mHasKeepGaps = False
End Sub
modExfUi.basMessages and status bar257 lines
Attribute VB_Name = "modExfUi"
' ExcelifyXML - what the user sees: messages (in the workbook's language, read
' from the plan: this file holds no French or English text), the save dialog,
' the status bar.
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary
Option Private Module

Private mMsgIndex As ExfStrMap
Private mMsgText() As String
Private mMsgCount As Long
Private mMsgReady As Boolean

Private mErrKey As String
Private mErrArgs() As String        ' placeholder name, value, name, value...
Private mErrArgCount As Long

' ----------------------------------------------------------------------------
' Messages
' ----------------------------------------------------------------------------

Public Sub ExfMessagesClear()
    ExfMapInit mMsgIndex, 64
    ReDim mMsgText(0 To 63)
    mMsgCount = 0
    mMsgReady = True
End Sub

Public Sub ExfMessageAdd(ByVal key As String, ByVal txt As String)
    Dim i As Long
    If Not mMsgReady Then ExfMessagesClear
    i = ExfMapGet(mMsgIndex, key)
    If i < 0 Then
        i = mMsgCount
        If i > UBound(mMsgText) Then ReDim Preserve mMsgText(0 To 2 * i)
        ExfMapSet mMsgIndex, key, i
        mMsgCount = i + 1
    End If
    mMsgText(i) = txt
End Sub

' The message in the workbook's language, or a short built-in text when the
' plan (and so every message) is missing.
Public Function ExfMessageText(ByVal key As String) As String
    Dim i As Long
    i = -1
    If mMsgReady Then i = ExfMapGet(mMsgIndex, key)
    If i >= 0 Then
        ExfMessageText = mMsgText(i)
    Else
        ExfMessageText = ExfFallbackText(key)
    End If
End Function

' Built-in texts, English then French (accents written as character codes:
' this file stays ASCII).
Private Function ExfFallbackText(ByVal key As String) As String
    Select Case key
        Case "title", "saveDialogTitle"
            ExfFallbackText = "ExcelifyXML"
        Case "fileFilterLabel"
            ExfFallbackText = "XML"
        Case "errPlanMissing"
            ExfFallbackText = "This workbook's structure information is missing or damaged. " & _
                "Start again from the downloaded workbook." & vbLf & vbLf & _
                "Les informations de structure de ce classeur sont manquantes ou ab" & ChrW(238) & "m" & ChrW(233) & "es. " & _
                "Repartez du classeur t" & ChrW(233) & "l" & ChrW(233) & "charg" & ChrW(233) & "."
        Case "errPlanTooNew"
            ExfFallbackText = "This workbook needs a newer version of the macro ({needed}). " & _
                "Generate a new workbook on excelifyxml.com." & vbLf & vbLf & _
                "Ce classeur demande une version plus r" & ChrW(233) & "cente de la macro ({needed}). " & _
                "G" & ChrW(233) & "n" & ChrW(233) & "rez un nouveau classeur sur excelifyxml.com."
        Case "errUnexpected"
            ExfFallbackText = "ExcelifyXML: {code} - {description}"
        Case Else
            ExfFallbackText = "ExcelifyXML: " & key
    End Select
End Function

' Replaces each {name} whose name is given (pairs name, value), in a single
' pass like fillText in workbook-texts.ts: an inserted value is never read
' again, an unknown placeholder is left as is.
Public Function ExfFill(ByVal template As String, ParamArray args() As Variant) As String
    Dim pairs() As String, n As Long, i As Long
    n = UBound(args) + 1
    If n > 0 Then
        ReDim pairs(0 To n - 1)
        For i = 0 To n - 1
            pairs(i) = CStr(args(i))
        Next i
    End If
    ExfFill = ExfFillPairs(template, pairs, n)
End Function

Private Function ExfFillPairs(ByVal template As String, ByRef pairs() As String, ByVal n As Long) As String
    Dim out As String, pos As Long, openAt As Long, closeAt As Long, nm As String, a As Long, found As Long
    pos = 1
    Do
        openAt = InStr(pos, template, "{", vbBinaryCompare)
        If openAt = 0 Then Exit Do
        closeAt = InStr(openAt + 1, template, "}", vbBinaryCompare)
        If closeAt = 0 Then Exit Do
        nm = Mid$(template, openAt + 1, closeAt - openAt - 1)
        found = -1
        If ExfIsWord(nm) Then
            For a = 0 To n - 2 Step 2
                If pairs(a) = nm Then
                    found = a + 1
                    Exit For
                End If
            Next a
        End If
        If found >= 0 Then
            out = out & Mid$(template, pos, openAt - pos) & pairs(found)
            pos = closeAt + 1
        Else
            out = out & Mid$(template, pos, openAt - pos + 1)
            pos = openAt + 1
        End If
    Loop
    ExfFillPairs = out & Mid$(template, pos)
End Function

' Placeholder names: letters, digits and underscores (\w in JavaScript).
Private Function ExfIsWord(ByRef s As String) As Boolean
    Dim i As Long, c As Long
    If Len(s) = 0 Then Exit Function
    For i = 1 To Len(s)
        c = ExfUnit(s, i)
        If Not ((c >= 48 And c <= 57) Or (c >= 65 And c <= 90) Or (c >= 97 And c <= 122) Or c = 95) Then Exit Function
    Next i
    ExfIsWord = True
End Function

' ----------------------------------------------------------------------------
' The message to show when the macro stops
' ----------------------------------------------------------------------------

Public Sub ExfSetError(ByVal key As String, ParamArray args() As Variant)
    Dim i As Long
    mErrKey = key
    mErrArgCount = UBound(args) + 1
    If mErrArgCount > 0 Then
        ReDim mErrArgs(0 To mErrArgCount - 1)
        For i = 0 To mErrArgCount - 1
            mErrArgs(i) = CStr(args(i))
        Next i
    End If
End Sub

Public Sub ExfClearError()
    mErrKey = vbNullString
    mErrArgCount = 0
End Sub

Public Function ExfErrorKey() As String
    ExfErrorKey = mErrKey
End Function

Public Function ExfErrorMessage() As String
    ExfErrorMessage = ExfFillPairs(ExfMessageText(mErrKey), mErrArgs, mErrArgCount)
End Function

' For the test benches: "ERR<TAB>key<TAB>name=value<TAB>..."
Public Function ExfErrorReport() As String
    Dim s As String, a As Long
    s = "ERR" & vbTab & mErrKey
    For a = 0 To mErrArgCount - 2 Step 2
        s = s & vbTab & mErrArgs(a) & "=" & mErrArgs(a + 1)
    Next a
    ExfErrorReport = s
End Function

' ----------------------------------------------------------------------------
' Where to write
' ----------------------------------------------------------------------------

' Save dialog, proposing "<source>-modifie.xml". Returns "" when cancelled.
' Mac: Excel may only write the very file chosen in this dialog (sandbox), and
' the dialog offers Excel's formats (.xlsx by default, no filter possible): the
' dialog is shown again until the user picks an XML format, so that the name
' it returns ends in .xml. Windows: an XML filter; extensionFixed tells whether
' the typed name had to be corrected to end in .xml.
Public Function ExfAskSavePath(ByVal folder As String, ByVal suggested As String, ByRef extensionFixed As Boolean) As String
    Dim p As Variant
#If Mac Then
    Do
        p = Application.GetSaveAsFilename(InitialFileName:=suggested)
        If VarType(p) = vbBoolean Then Exit Function
        If LCase$(Right$(CStr(p), 4)) = ".xml" Then Exit Do
        If MsgBox(ExfMessageText("macChooseXml"), vbOKCancel + vbInformation, ExfMessageText("title")) <> vbOK Then Exit Function
    Loop
    ExfAskSavePath = CStr(p)
#Else
    If Len(folder) > 0 And Not ExfIsCloudPath(folder) Then suggested = folder & Application.PathSeparator & suggested
    p = Application.GetSaveAsFilename(InitialFileName:=suggested, _
        FileFilter:=ExfMessageText("fileFilterLabel") & " (*.xml),*.xml", Title:=ExfMessageText("saveDialogTitle"))
    If VarType(p) = vbBoolean Then Exit Function
    ExfAskSavePath = ExfXmlPath(CStr(p), extensionFixed)
#End If
End Function

Public Function ExfXmlPath(ByVal filePath As String, ByRef extensionFixed As Boolean) As String
    If LCase$(Right$(filePath, 5)) = ".xlsx" Then
        filePath = Left$(filePath, Len(filePath) - 5)
        extensionFixed = True
    End If
    If LCase$(Right$(filePath, 4)) <> ".xml" Then
        filePath = filePath & ".xml"
        extensionFixed = True
    End If
    ExfXmlPath = filePath
End Function

Public Function ExfIsCloudPath(ByVal filePath As String) As Boolean
    Dim s As String
    s = LCase$(Left$(filePath, 8))
    ExfIsCloudPath = (Left$(s, 7) = "http://" Or s = "https://")
End Function

' Windows: file names go through the ANSI code page in VBA; a character it
' can't hold (emoji, other alphabets) would silently become "?".
Public Function ExfPathEncodable(ByVal filePath As String) As Boolean
#If Mac Then
    ExfPathEncodable = True
#Else
    ExfPathEncodable = (StrConv(StrConv(filePath, vbFromUnicode), vbUnicode) = filePath)
#End If
End Function

Public Function ExfFileExists(ByVal filePath As String) As Boolean
    On Error Resume Next
    ExfFileExists = Len(Dir$(filePath)) > 0
End Function

Public Function ExfFileName(ByVal filePath As String) As String
    Dim i As Long
    i = InStrRev(filePath, Application.PathSeparator)
    If i = 0 Then i = InStrRev(filePath, "/")
    ExfFileName = Mid$(filePath, i + 1)
End Function

' ----------------------------------------------------------------------------
' Status bar
' ----------------------------------------------------------------------------

Public Sub ExfStatus(ByVal msg As String)
    On Error Resume Next
    Application.StatusBar = msg
End Sub

Public Sub ExfStatusClear()
    On Error Resume Next
    Application.StatusBar = False
End Sub
modExfUtf8.basUTF-8 encoding and writing the file108 lines
Attribute VB_Name = "modExfUtf8"
' ExcelifyXML - UTF-8 encoding and file output in native VBA (Windows + Mac).
' No COM object, no Declare, no network: nothing that an antivirus heuristic or
' the Mac sandbox objects to.
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Private Module

' Encode a string (UTF-16 inside VBA) as UTF-8 bytes. A surrogate pair becomes
' a 4-byte sequence and a lone surrogate becomes U+FFFD (EF BF BD), exactly like
' the TextEncoder used by the website, so both outputs are byte-identical.
Public Function ExfUtf8(ByRef s As String) As Byte()
    Dim src() As Byte, out() As Byte
    Dim n As Long, i As Long, j As Long
    Dim c As Long, c2 As Long, cp As Long

    If Len(s) = 0 Then
        ExfUtf8 = out
        Exit Function
    End If
    src = s                                 ' UTF-16LE code units, 2 bytes each
    n = (UBound(src) + 1) \ 2
    ReDim out(0 To n * 3 - 1)               ' worst case: 3 bytes per code unit

    Do While i < n
        c = src(2 * i) Or (CLng(src(2 * i + 1)) * &H100&)
        If c < &H80& Then
            out(j) = c
            j = j + 1
        ElseIf c < &H800& Then
            out(j) = &HC0& Or (c \ &H40&)
            out(j + 1) = &H80& Or (c And &H3F&)
            j = j + 2
        ElseIf c >= &HD800& And c <= &HDFFF& Then
            c2 = -1
            If c <= &HDBFF& And i + 1 < n Then c2 = src(2 * i + 2) Or (CLng(src(2 * i + 3)) * &H100&)
            If c2 >= &HDC00& And c2 <= &HDFFF& Then
                cp = &H10000 + (c - &HD800&) * &H400& + (c2 - &HDC00&)
                out(j) = &HF0& Or (cp \ &H40000)
                out(j + 1) = &H80& Or ((cp \ &H1000&) And &H3F&)
                out(j + 2) = &H80& Or ((cp \ &H40&) And &H3F&)
                out(j + 3) = &H80& Or (cp And &H3F&)
                j = j + 4
                i = i + 1                   ' the low surrogate is consumed
            Else
                out(j) = &HEF&              ' lone surrogate -> U+FFFD
                out(j + 1) = &HBF&
                out(j + 2) = &HBD&
                j = j + 3
            End If
        Else
            out(j) = &HE0& Or (c \ &H1000&)
            out(j + 1) = &H80& Or ((c \ &H40&) And &H3F&)
            out(j + 2) = &H80& Or (c And &H3F&)
            j = j + 3
        End If
        i = i + 1
    Loop

    ReDim Preserve out(0 To j - 1)
    ExfUtf8 = out
End Function

' Number of bytes in an array that may be unallocated (empty string case).
Public Function ExfByteCount(ByRef data() As Byte) As Long
    On Error GoTo NoData
    ExfByteCount = UBound(data) - LBound(data) + 1
    Exit Function
NoData:
    ExfByteCount = 0
End Function

' Open a temporary file next to the target, for sequential binary writes.
' "Open ... For Binary" does not truncate an existing file, hence the temporary
' file that ExfWriterCommit renames over the target at the end.
Public Function ExfWriterOpen(ByVal targetPath As String) As Integer
    Dim f As Integer
    On Error Resume Next
    Kill targetPath & ".tmp"
    On Error GoTo 0
    f = FreeFile
    Open targetPath & ".tmp" For Binary Access Write As #f
    ExfWriterOpen = f
End Function

' Mac: Excel may only write the file chosen in the save dialog - not a
' temporary file next to it - so that file is written in place: emptied first
' (Open ... For Output), then filled.
Public Function ExfWriterOpenInPlace(ByVal targetPath As String) As Integer
    Dim f As Integer
    f = FreeFile
    Open targetPath For Output As #f
    Close #f
    f = FreeFile
    Open targetPath For Binary Access Write As #f
    ExfWriterOpenInPlace = f
End Function

Public Sub ExfWriterPut(ByVal f As Integer, ByRef data() As Byte)
    If ExfByteCount(data) > 0 Then Put #f, , data
End Sub

Public Sub ExfWriterCommit(ByVal f As Integer, ByVal targetPath As String)
    Close #f
    If Len(Dir$(targetPath)) > 0 Then Kill targetPath
    Name targetPath & ".tmp" As targetPath
End Sub
modExfWrite.basRebuilding the XML (4/4): writing the tree out, formatted exactly like the website213 lines
Attribute VB_Name = "modExfWrite"
' ExcelifyXML - the reconstruction engine, part 4: writes the element tree
' (modExfTree) as XML. Port of emit in src/lib/excel-macro/engine/execute.ts
' (reconstruct.ts emitElement): UTF-8 without BOM, one line per element,
' same indentation, escaping and CDATA sections as the website.
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary
Option Private Module

Private Const BUF_SIZE As Long = 1048576   ' characters encoded and written at a time

Private mBuf As String
Private mBufPos As Long
Private mOutFile As Integer
Private mOutBytes As Double
Private mCleanOutput As Boolean     ' a plan string holds a character XML forbids

' Writes the XML to an open file (modExfUtf8), UTF-8 without BOM, one line per
' element, "\n" after each line. Returns the number of bytes written.
Public Function ExfWriteXml(ByRef p As ExfPlan, ByVal fileNo As Integer) As Double
    Dim unitText As String, pads() As String, padCount As Long
    Dim stNode() As Long, stStatic() As Boolean, stDepth() As Long, stClose() As Boolean, sp As Long
    Dim kids() As Long, kidCount As Long
    Dim id As Long, node As Long, isStatic As Boolean, depth As Long, closing As Boolean
    Dim nm As String, txt As String, selfClosing As Boolean, cdata As Boolean
    Dim a As Long, c As Long, i As Long

    mOutFile = fileNo
    mOutBytes = 0
    mCleanOutput = p.cleanOutput
    mBuf = Space$(BUF_SIZE)
    mBufPos = 1
    For i = 0 To p.prologueCount - 1
        ExfOut p.strs(p.prologue(i))
        ExfOut vbLf
    Next i

    unitText = p.strs(p.indent)
    ReDim pads(0 To 63)
    padCount = 1
    ReDim kids(0 To 63)
    ReDim stNode(0 To 1023)
    ReDim stStatic(0 To 1023)
    ReDim stDepth(0 To 1023)
    ReDim stClose(0 To 1023)
    stNode(0) = ExfTreeRoot()
    sp = 1

    Do While sp > 0
        sp = sp - 1
        id = stNode(sp)
        isStatic = stStatic(sp)
        depth = stDepth(sp)
        closing = stClose(sp)

        ' A tree node referring to a kept element is emitted from the plan.
        node = id
        If Not isStatic Then
            If nStatic(id) >= 0 Then
                node = nStatic(id)
                isStatic = True
            End If
        End If
        If isStatic Then nm = p.strs(p.nodeName(node)) Else nm = ExfTreeNameText(p, nNameId(node))

        Do While padCount <= depth
            If padCount > UBound(pads) Then ReDim Preserve pads(0 To 2 * padCount)
            pads(padCount) = pads(padCount - 1) & unitText
            padCount = padCount + 1
        Loop

        If closing Then
            ExfOut pads(depth)
            ExfOut "</"
            ExfOut nm
            ExfOut ">" & vbLf
        Else
            ExfOut pads(depth)
            ExfOut "<"
            ExfOut nm
            kidCount = 0
            If isStatic Then
                For a = p.nodeAttrStart(node) To p.nodeAttrStart(node) + p.nodeAttrCount(node) - 1
                    ExfOut " "
                    ExfOut p.strs(p.nodeAttrs(2 * a))
                    ExfOut "="""
                    ExfOut ExfEncodeAttr(p.strs(p.nodeAttrs(2 * a + 1)))
                    ExfOut """"
                Next a
                For c = p.nodeChildStart(node) To p.nodeChildStart(node) + p.nodeChildCount(node) - 1
                    If kidCount > UBound(kids) Then ReDim Preserve kids(0 To 2 * kidCount)
                    kids(kidCount) = p.nodeChildren(c)
                    kidCount = kidCount + 1
                Next c
                txt = p.strs(p.nodeText(node))
                selfClosing = (p.nodeSelfClosing(node) = 1)
                cdata = False
            Else
                a = nAttrFirst(node)
                Do While a >= 0
                    ExfOut " "
                    ' A plan string, or a renamed attribute's new name (macro 3.3).
                    ExfOut ExfTreeNameText(p, aKeyId(a))
                    ExfOut "="""
                    ExfOut ExfEncodeAttr(aVal(a))
                    ExfOut """"
                    a = aNext(a)
                Loop
                c = nFirst(node)
                Do While c >= 0
                    If Not nRemoved(c) Then
                        If kidCount > UBound(kids) Then ReDim Preserve kids(0 To 2 * kidCount)
                        kids(kidCount) = c
                        kidCount = kidCount + 1
                    End If
                    c = nNext(c)
                Loop
                txt = nText(node)
                selfClosing = nSelf(node)
                cdata = nCdata(node)
            End If

            If kidCount = 0 Then
                If Len(txt) = 0 Then
                    If selfClosing Then
                        ExfOut "/>" & vbLf
                    Else
                        ExfOut "></"
                        ExfOut nm
                        ExfOut ">" & vbLf
                    End If
                Else
                    ExfOut ">"
                    If ExfWantsCdata(txt, cdata) Then ExfOut ExfCdata(txt) Else ExfOut ExfEncodeText(txt)
                    ExfOut "</"
                    ExfOut nm
                    ExfOut ">" & vbLf
                End If
            Else
                ExfOut ">" & vbLf
                If sp + kidCount + 1 > UBound(stNode) Then
                    ReDim Preserve stNode(0 To 2 * (sp + kidCount + 1))
                    ReDim Preserve stStatic(0 To 2 * (sp + kidCount + 1))
                    ReDim Preserve stDepth(0 To 2 * (sp + kidCount + 1))
                    ReDim Preserve stClose(0 To 2 * (sp + kidCount + 1))
                End If
                stNode(sp) = node
                stStatic(sp) = isStatic
                stDepth(sp) = depth
                stClose(sp) = True
                sp = sp + 1
                For c = kidCount - 1 To 0 Step -1
                    stNode(sp) = kids(c)
                    stStatic(sp) = isStatic
                    stDepth(sp) = depth + 1
                    stClose(sp) = False
                    sp = sp + 1
                Next c
            End If
        End If
    Loop

    ExfFlushOut
    mBuf = vbNullString
    ExfWriteXml = mOutBytes
End Function

' Appends to the output buffer. When a plan string holds characters XML
' forbids (U+FFFE and U+FFFF pass the upload), each piece is cleaned as the
' site's final pass cleans its XML (execute.ts emit): the same thing, a
' surrogate pair never straddling two pieces.
Private Sub ExfOut(ByRef s As String)
    Dim removed() As Long, removedCount As Long
    If mCleanOutput Then
        If ExfMayHoldInvalid(s) Then
            ReDim removed(0 To 7)
            ExfOutRaw ExfCleanInvalid(s, removed, removedCount)
            Exit Sub
        End If
    End If
    ExfOutRaw s
End Sub

' Appends to the output buffer (Mid$ writes in place: no new string per piece).
' A piece is never cut, so a surrogate pair never straddles two writes.
Private Sub ExfOutRaw(ByRef s As String)
    Dim n As Long
    n = Len(s)
    If n = 0 Then Exit Sub
    If mBufPos + n - 1 > BUF_SIZE Then
        ExfFlushOut
        If n > BUF_SIZE Then
            ExfWriteChunk s
            Exit Sub
        End If
    End If
    Mid$(mBuf, mBufPos, n) = s
    mBufPos = mBufPos + n
End Sub

Private Sub ExfFlushOut()
    If mBufPos > 1 Then ExfWriteChunk Left$(mBuf, mBufPos - 1)
    mBufPos = 1
End Sub

Private Sub ExfWriteChunk(ByRef s As String)
    Dim bytes() As Byte
    bytes = ExfUtf8(s)
    ExfWriterPut mOutFile, bytes
    mOutBytes = mOutBytes + ExfByteCount(bytes)
End Sub
modExfXml.basXML text rules: tag names, character escaping, CDATA sections426 lines
Attribute VB_Name = "modExfXml"
' ExcelifyXML - text rules of the XML output, character by character: XML
' names, escaping, CDATA sections, trimming. Port of
' src/lib/excel-macro/engine/text.ts, where each function is proven equal to
' the website's online reconstruction over all of Unicode.
' (c) To The Rock SASU - licensed for use with ExcelifyXML workbooks only.
' This file must stay 7-bit ASCII: the VBA editor imports modules as ANSI.
Option Explicit
Option Compare Binary
Option Private Module

Private mBadPattern As String           ' Like pattern of ExfMayHoldInvalid, built once

' UTF-16 code unit at position i (1-based), 0 to 65535 (AscW is signed).
Public Function ExfUnit(ByRef s As String, ByVal i As Long) As Long
    ExfUnit = AscW(Mid$(s, i, 1)) And &HFFFF&
End Function

' XML 1.0 name start characters (text.ts NAME_START, code units).
Private Function ExfIsNameStart(ByVal c As Long) As Boolean
    Select Case c
        Case &H41& To &H5A&, &H5F&, &H61& To &H7A&, &HC0& To &HD6&, &HD8& To &HF6&, _
             &HF8& To &H2FF&, &H370& To &H37D&, &H37F& To &H1FFF&, &H200C& To &H200D&, _
             &H2070& To &H218F&, &H2C00& To &H2FEF&, &H3001& To &HD7FF&, &HF900& To &HFDCF&, _
             &HFDF0& To &HFFFD&
            ExfIsNameStart = True
    End Select
End Function

' Characters also allowed after the first one (text.ts NAME_MORE).
Private Function ExfIsNameMore(ByVal c As Long) As Boolean
    Select Case c
        Case &H2D&, &H2E&, &H30& To &H3A&, &HB7&, &H300& To &H36F&, &H203F& To &H2040&
            ExfIsNameMore = True
    End Select
End Function

' = text.ts isXmlName: astral characters U+10000-U+EFFFF allowed as surrogate
' pairs, lone surrogates refused.
Public Function ExfIsXmlName(ByRef nm As String) As Boolean
    Dim i As Long, n As Long, c As Long, lo As Long, ok As Boolean, first As Boolean
    n = Len(nm)
    If n = 0 Then Exit Function
    i = 1
    first = True
    Do While i <= n
        c = ExfUnit(nm, i)
        If c >= &HD800& And c <= &HDBFF& Then
            lo = 0
            If i + 1 <= n Then lo = ExfUnit(nm, i + 1)
            If lo < &HDC00& Or lo > &HDFFF& Then Exit Function
            ok = (c <= &HDB7F&)
            i = i + 2
        ElseIf c >= &HDC00& And c <= &HDFFF& Then
            Exit Function
        Else
            ok = ExfIsNameStart(c)
            If Not ok And Not first Then ok = ExfIsNameMore(c)
            i = i + 1
        End If
        If Not ok Then Exit Function
        first = False
    Loop
    ExfIsXmlName = True
End Function

' = text.ts trimWith: String.prototype.trim, isSpace() listing the code units
' it removes (plan table SPACE).
Public Function ExfTrim(ByRef aValue As String, ByRef isSpace() As Boolean) As String
    Dim s As Long, e As Long
    s = 1
    e = Len(aValue)
    Do While s <= e
        If Not isSpace(ExfUnit(aValue, s)) Then Exit Do
        s = s + 1
    Loop
    Do While e >= s
        If Not isSpace(ExfUnit(aValue, e)) Then Exit Do
        e = e - 1
    Loop
    ExfTrim = Mid$(aValue, s, e - s + 1)
End Function

' = text.ts upperWith: toUpperCase restricted to the code units that can be
' part of a boolean token (plan table CASE); every other one is kept.
Public Function ExfUpperForTokens(ByRef aValue As String, ByRef hasUpper() As Boolean, ByRef upper() As String) As String
    Dim i As Long, n As Long, c As Long, parts() As String
    n = Len(aValue)
    If n = 0 Then Exit Function
    ReDim parts(0 To n - 1)
    For i = 1 To n
        c = ExfUnit(aValue, i)
        If hasUpper(c) Then
            parts(i - 1) = upper(c)
        Else
            parts(i - 1) = Mid$(aValue, i, 1)
        End If
    Next i
    ExfUpperForTokens = Join(parts, vbNullString)
End Function

' = text.ts encodeText (parser.ts encodeXmlText). Replacing "&" first, then the
' others, gives the same result as the website's character-by-character loop.
Public Function ExfEncodeText(ByRef s As String) As String
    If InStr(1, s, "&", vbBinaryCompare) = 0 And InStr(1, s, "<", vbBinaryCompare) = 0 And _
       InStr(1, s, ">", vbBinaryCompare) = 0 And InStr(1, s, vbCr, vbBinaryCompare) = 0 Then
        ExfEncodeText = s
        Exit Function
    End If
    ExfEncodeText = Replace(Replace(Replace(Replace(s, "&", "&amp;"), "<", "&lt;"), ">", "&gt;"), vbCr, "&#13;")
End Function

' = text.ts encodeAttr (parser.ts encodeXmlAttr).
Public Function ExfEncodeAttr(ByRef s As String) As String
    If InStr(1, s, "&", vbBinaryCompare) = 0 And InStr(1, s, "<", vbBinaryCompare) = 0 And _
       InStr(1, s, """", vbBinaryCompare) = 0 And InStr(1, s, vbTab, vbBinaryCompare) = 0 And _
       InStr(1, s, vbLf, vbBinaryCompare) = 0 And InStr(1, s, vbCr, vbBinaryCompare) = 0 Then
        ExfEncodeAttr = s
        Exit Function
    End If
    ExfEncodeAttr = Replace(Replace(Replace(Replace(Replace(Replace(s, "&", "&amp;"), "<", "&lt;"), _
        """", "&quot;"), vbTab, "&#9;"), vbLf, "&#10;"), vbCr, "&#13;")
End Function

' = text.ts wantsCdata (parser.ts shouldUseCdata): CDATA in the source, or at
' least two angle brackets.
Public Function ExfWantsCdata(ByRef s As String, ByVal wasCdata As Boolean) As Boolean
    Dim lt As Long, gt As Long
    If wasCdata Then
        ExfWantsCdata = True
        Exit Function
    End If
    lt = InStr(1, s, "<", vbBinaryCompare)
    gt = InStr(1, s, ">", vbBinaryCompare)
    If lt = 0 And gt = 0 Then Exit Function
    If lt > 0 And gt > 0 Then
        ExfWantsCdata = True
    ElseIf lt > 0 Then
        ExfWantsCdata = InStr(lt + 1, s, "<", vbBinaryCompare) > 0
    Else
        ExfWantsCdata = InStr(gt + 1, s, ">", vbBinaryCompare) > 0
    End If
End Function

' = text.ts cdataSection: a literal "]]>" is split across two sections, and a
' CR goes between two sections as &#13; (inside, XML readers would read a line
' break). "]]>" holds no CR, so replacing it first matches the website's loop.
Public Function ExfCdata(ByRef s As String) As String
    ExfCdata = "<![CDATA[" & Replace(Replace(s, "]]>", "]]]]><![CDATA[>"), vbCr, "]]>&#13;<![CDATA[") & "]]>"
End Function

' = text.ts lenKey: unambiguous key part "<length>:<value>".
Public Function ExfLenKey(ByRef aValue As String) As String
    ExfLenKey = Len(aValue) & ":" & aValue
End Function

' = text.ts isDigits (value-repairs.ts isDigits): ASCII digits only, at least
' one ("0012345"). Like compares code units here (Option Compare Binary).
Public Function ExfIsDigits(ByRef aValue As String) As Boolean
    If Len(aValue) = 0 Then Exit Function
    ExfIsDigits = Not (aValue Like "*[!0-9]*")
End Function

' Order of two strings by UTF-16 code units, like JavaScript's < and >:
' -1, 0 or 1.
Public Function ExfCompareUnits(ByRef a As String, ByRef b As String) As Long
    Dim i As Long, n As Long, ca As Long, cb As Long
    n = Len(a)
    If Len(b) < n Then n = Len(b)
    For i = 1 To n
        ca = ExfUnit(a, i)
        cb = ExfUnit(b, i)
        If ca <> cb Then
            If ca < cb Then ExfCompareUnits = -1 Else ExfCompareUnits = 1
            Exit Function
        End If
    Next i
    If Len(a) < Len(b) Then
        ExfCompareUnits = -1
    ElseIf Len(a) > Len(b) Then
        ExfCompareUnits = 1
    End If
End Function

' = execute.ts attrSignature: same attributes <=> same signature, whatever
' their order (keys sorted by code units, like Array.prototype.sort).
Public Function ExfAttrSig(ByRef keys() As String, ByRef vals() As String, ByVal n As Long) As String
    Dim order() As Long, parts() As String, i As Long, j As Long
    If n = 0 Then Exit Function
    ReDim order(0 To n - 1)
    For i = 0 To n - 1
        j = i
        Do While j > 0
            If ExfCompareUnits(keys(order(j - 1)), keys(i)) <= 0 Then Exit Do
            order(j) = order(j - 1)
            j = j - 1
        Loop
        order(j) = i
    Next i
    ReDim parts(0 To 2 * n - 1)
    For i = 0 To n - 1
        parts(2 * i) = ExfLenKey(keys(order(i)))
        parts(2 * i + 1) = ExfLenKey(vals(order(i)))
    Next i
    ExfAttrSig = Join(parts, vbNullString)
End Function

' Excel column letters of a 1-based column number (28 -> AB).
Public Function ExfColumnLetters(ByVal n As Long) As String
    Dim s As String
    Do While n > 0
        s = Chr$(65 + (n - 1) Mod 26) & s
        n = (n - 1) \ 26
    Loop
    ExfColumnLetters = s
End Function

' = text.ts mayHoldInvalid: a C0 control other than tab, LF and CR, U+FFFE,
' U+FFFF or a surrogate (paired ones are kept by ExfCleanInvalid). Like and
' InStr run in Excel's own code: a quick sort before the exact clean-up.
Public Function ExfMayHoldInvalid(ByRef s As String) As Boolean
    If Len(mBadPattern) = 0 Then
        mBadPattern = "*[" & ChrW(1) & "-" & ChrW(8) & ChrW(11) & ChrW(12) & ChrW(14) & "-" & ChrW(31) & _
            ChrW(&HD800&) & "-" & ChrW(&HDFFF&) & ChrW(&HFFFE&) & ChrW(&HFFFF&) & "]*"
    End If
    If InStr(1, s, vbNullChar, vbBinaryCompare) > 0 Then
        ExfMayHoldInvalid = True
    Else
        ExfMayHoldInvalid = (s Like mBadPattern)
    End If
End Function

' = text.ts cleanInvalid (reconstruct.ts cleanInvalidCharacters): U+000B and
' U+000C, Word's line and page breaks, become LF; the other characters XML 1.0
' forbids - C0 controls, U+FFFE, U+FFFF, a surrogate without its pair - are
' taken out, their code units added to removed() (allocated by the caller).
Public Function ExfCleanInvalid(ByRef s As String, ByRef removed() As Long, ByRef removedCount As Long) As String
    Dim i As Long, n As Long, c As Long, lo As Long, k As Long, parts() As String
    n = Len(s)
    If n = 0 Then Exit Function
    ReDim parts(0 To n - 1)
    i = 1
    Do While i <= n
        c = ExfUnit(s, i)
        If c = 11 Or c = 12 Then
            parts(k) = vbLf
            k = k + 1
            i = i + 1
        ElseIf (c < 32 And c <> 9 And c <> 10 And c <> 13) Or c = &HFFFE& Or c = &HFFFF& Then
            ExfAddUnit removed, removedCount, c
            i = i + 1
        ElseIf c >= &HD800& And c <= &HDBFF& Then
            lo = 0
            If i < n Then lo = ExfUnit(s, i + 1)
            If lo >= &HDC00& And lo <= &HDFFF& Then
                parts(k) = Mid$(s, i, 2)
                k = k + 1
                i = i + 2
            Else
                ExfAddUnit removed, removedCount, c
                i = i + 1
            End If
        ElseIf c >= &HDC00& And c <= &HDFFF& Then
            ExfAddUnit removed, removedCount, c
            i = i + 1
        Else
            parts(k) = Mid$(s, i, 1)
            k = k + 1
            i = i + 1
        End If
    Loop
    If k = 0 Then Exit Function
    ReDim Preserve parts(0 To k - 1)
    ExfCleanInvalid = Join(parts, vbNullString)
End Function

Private Sub ExfAddUnit(ByRef removed() As Long, ByRef removedCount As Long, ByVal c As Long)
    If removedCount > UBound(removed) Then ReDim Preserve removed(0 To 2 * removedCount + 1)
    removed(removedCount) = c
    removedCount = removedCount + 1
End Sub

' = text.ts unitCode: "U+000B", how the site names a character.
Public Function ExfUnitCode(ByVal c As Long) As String
    ExfUnitCode = "U+" & Right$("000" & Hex$(c), 4)
End Function

' ---------------------------------------------------------------------------
' Macro 3.1 (plan format 4): the shapes of numbers and the error words the
' site's value repairs read with regular expressions (text.ts decimalsOf,
' isScientificCode, plainNumber, isErrorWord).
' ---------------------------------------------------------------------------

' = text.ts decimalsOf (value-repairs.ts DECIMAL): the count of decimals of
' "19.90", "0,5", "42" (2, 1, 0) - an optional minus, 0 or digits without a
' leading zero, then a point or a comma and 1 or 2 digits -, -1 for anything
' else ("05", "1.", "1.250", "1 250").
Public Function ExfDecimalsOf(ByRef aValue As String) As Long
    Dim n As Long, i As Long, c As Long, k As Long
    ExfDecimalsOf = -1
    n = Len(aValue)
    i = 1
    If n > 0 Then
        If ExfUnit(aValue, 1) = 45 Then i = 2
    End If
    If i > n Then Exit Function
    c = ExfUnit(aValue, i)
    If c = 48 Then
        i = i + 1
    ElseIf c >= 49 And c <= 57 Then
        i = i + 1
        Do While i <= n
            c = ExfUnit(aValue, i)
            If c < 48 Or c > 57 Then Exit Do
            i = i + 1
        Loop
    Else
        Exit Function
    End If
    If i > n Then
        ExfDecimalsOf = 0
        Exit Function
    End If
    c = ExfUnit(aValue, i)
    If c <> 46 And c <> 44 Then Exit Function
    If n - i < 1 Or n - i > 2 Then Exit Function
    For k = i + 1 To n
        c = ExfUnit(aValue, k)
        If c < 48 Or c > 57 Then Exit Function
    Next k
    ExfDecimalsOf = n - i
End Function

' = text.ts isScientificCode (value-repairs.ts SCIENTIFIC_CODE): digits, E or
' e, an optional sign, 1 to 3 digits ("12E3", "1e10", "10E-2").
Public Function ExfIsScientificCode(ByRef aValue As String) As Boolean
    Dim n As Long, i As Long, c As Long, k As Long
    n = Len(aValue)
    i = 1
    Do While i <= n
        c = ExfUnit(aValue, i)
        If c < 48 Or c > 57 Then Exit Do
        i = i + 1
    Loop
    If i = 1 Or i > n Then Exit Function
    c = ExfUnit(aValue, i)
    If c <> 69 And c <> 101 Then Exit Function
    i = i + 1
    If i <= n Then
        c = ExfUnit(aValue, i)
        If c = 43 Or c = 45 Then i = i + 1
    End If
    If n - i + 1 < 1 Or n - i + 1 > 3 Then Exit Function
    For k = i To n
        c = ExfUnit(aValue, k)
        If c < 48 Or c > 57 Then Exit Function
    Next k
    ExfIsScientificCode = True
End Function

' = text.ts plainNumber (value-repairs.ts plainNumberOf): a number a
' spreadsheet wrote, as the site writes the number a code like "12E3" stands
' for - "12000", "0,1" -> "0.1", "0012.500" -> "12.5" -; "" for anything else
' and past 15 digits. From the digits, never through a Double.
Public Function ExfPlainNumber(ByRef aValue As String) As String
    Dim n As Long, i As Long, c As Long, k As Long, intEnd As Long, fracStart As Long, a As Long, b As Long
    Dim intPart As String, fracPart As String
    n = Len(aValue)
    If n > 30 Then Exit Function
    i = 1
    Do While i <= n
        c = ExfUnit(aValue, i)
        If c < 48 Or c > 57 Then Exit Do
        i = i + 1
    Loop
    If i = 1 Then Exit Function
    intEnd = i - 1
    fracStart = n + 1
    If i <= n Then
        c = ExfUnit(aValue, i)
        If c <> 46 And c <> 44 Then Exit Function
        fracStart = i + 1
        If fracStart > n Then Exit Function
        For k = fracStart To n
            c = ExfUnit(aValue, k)
            If c < 48 Or c > 57 Then Exit Function
        Next k
    End If
    ' The integer's leading zeros (one digit kept), the fraction's trailing zeros.
    a = 1
    Do While a < intEnd
        If ExfUnit(aValue, a) <> 48 Then Exit Do
        a = a + 1
    Loop
    b = n
    Do While b >= fracStart
        If ExfUnit(aValue, b) <> 48 Then Exit Do
        b = b - 1
    Loop
    intPart = Mid$(aValue, a, intEnd - a + 1)
    If fracStart <= n Then fracPart = Mid$(aValue, fracStart, b - fracStart + 1)
    If Len(intPart) + Len(fracPart) > 15 Then Exit Function
    If Len(fracPart) = 0 Then ExfPlainNumber = intPart Else ExfPlainNumber = intPart & "." & fracPart
End Function

' = text.ts isErrorWord (value-shapes.ts isSpreadsheetError): a spreadsheet's
' error word, spaces around it left aside - one of the plan's ERRWORD table
' ("#N/A", "#NOM?"...) or "Err:5" and two digits (LibreOffice); 12 units at
' most, spaces included.
Public Function ExfIsErrorWord(ByRef aValue As String, ByRef isSpace() As Boolean, ByRef words As ExfStrMap) As Boolean
    Dim t As String, c As Long
    If Len(aValue) > 12 Then Exit Function
    t = ExfTrim(aValue, isSpace)
    If Len(t) = 0 Then Exit Function
    If ExfUnit(t, 1) = 35 Then
        ExfIsErrorWord = (ExfMapGet(words, t) >= 0)
    ElseIf Len(t) = 7 Then
        If Left$(t, 5) = "Err:5" Then
            c = ExfUnit(t, 6)
            If c >= 48 And c <= 57 Then
                c = ExfUnit(t, 7)
                ExfIsErrorWord = (c >= 48 And c <= 57)
            End If
        End If
    End If
End Function

If your organization forbids macros

Respect that choice: once edited, the workbook can be dropped on the online reconstruction page, which reads its data without running the macro; every generation also includes the standard bundle (CSV + manifest), which rebuilds online, without macros.

If your IT department wants to allow these workbooks, it's their call, after reviewing the code. Microsoft recommends granting this kind of exception sparingly.

A question from your IT department?

Write to us: we answer technical and security questions within one business day.

A free account is needed to try it: it holds your credits.

  • 3 free credits when you sign up
  • then 1 free credit every week
  • no credit card
  • no advertising emails without your consent