craft-xlsx: VBA function names and macro descriptions in binary workbooks

An Excel probe with VBA enabled showed two things the names reader got
wrong:

- Excel writes a VBA function a cell calls as a BrtName with fFunc, fOB and
  fProc, no formula, and none of the four strings fProc names otherwise
  carry. The reader refused it, which dropped every name and left every
  formula as its saved result. Such a name now ends after its comment; it
  stays out of the names, as .xlsm lists none, and cells calling it spell it.
- The two middle strings of a macro's name are its description and help
  topic, as .xlsm writes them (description="Function A" help="!0"), not the
  custom menu and description the specification's labels say.
This commit is contained in:
kiwi4boy committed 2026-11-14 12:21:06 -05:00
1 parent b11a5a38b8
commit b5eda42a33
3 files changed
+78 -29

No files matched your search

+20 -19
View File
@@ -83,25 +83,26 @@ for new pictures (`vm = i + 1`) and the `XLDAPR` dynamic-array metadata (`cm = 1
The parts this crate writes use the transitional namespaces; a strict file's kept parts stay as
they were. A binary workbook is not written.
A binary workbook gives the same `Workbook`, strings, rows and merged cells. Its styles are not
read (each cell keeps its format index). Its defined names are those of `definedNames` in the
`.xlsx` Excel writes: built-in names as `_xlnm.Print_Area`, sheet-scoped names with their
`localSheetId`, relative references as the cell they reach from A1, macro names with their
`function`, `xlm`, `functionGroupId` and `shortcutKey`. Excel's hidden names for newer functions
and LET parameters are left out, as in `.xlsx`, and so is the formula-less workbook-level built-in
Excel writes beside a sheet's (`Database`), which formulas still spell `_xlnm.Database`; a name
whose formula can't be read is left out with a warning. A reference may name an XLM macro sheet
(`Macro1!$A$1`, where macro names point), and a 3-D span is spelled by its ends whatever chart
sheets lie between them. Its cell formulas are decoded from their tokens into the text an `.xlsx`
file holds (`_xlfn.` and `_xlpm.` names as written, apart from the four ISO/IEC 29500 functions
`.xlsx` names bare, no implicit `@`, the spaces and line breaks typed in the formula, numbers as
Excel spells them), with
`FormulaKind::Shared` or `FormulaKind::Array` and their ranges, and `BrtCellMeta` as the cell
metadata index. Every cell of a shared formula gets its own text, decoded at the cell, since the
file keeps the tokens once. A formula whose decoding needs something the reader does not read
keeps only its saved result, with a warning saying why: a defined name left out, table references,
other workbooks, Python code stored outside the cell, data tables. The XLSB function table
(`xlsb/ftab.rs`) and the expression printer are this crate's own, apart from `craft-xls`'s.
A binary workbook gives the same `Workbook`, strings, rows and merged cells. Its styles are not read
(each cell keeps its format index). Its defined names are those of `definedNames` in the `.xlsx`
Excel writes: built-in names as `_xlnm.Print_Area`, sheet-scoped names with their `localSheetId`,
relative references as the cell they reach from A1, macro names with their `function`, `xlm` or
`vbProcedure`, `functionGroupId`, `shortcutKey`, `description` and `help`. Excel's hidden names for
newer functions and LET parameters are left out, as in `.xlsx`, and so is the formula-less
workbook-level built-in Excel writes beside a sheet's (`Database`), which formulas still spell
`_xlnm.Database`, and the formula-less name of a VBA function a cell calls (`.xlsm` lists none; the
cell spells it); a name whose formula can't be read is left out with a warning. A reference may name
an XLM macro sheet (`Macro1!$A$1`, where macro names point), and a 3-D span is spelled by its ends
whatever chart sheets lie between them. Its cell formulas are decoded from their tokens into the
text an `.xlsx` file holds (`_xlfn.` and `_xlpm.` names as written, apart from the four ISO/IEC
29500 functions `.xlsx` names bare, no implicit `@`, the spaces and line breaks typed in the
formula, numbers as Excel spells them), with `FormulaKind::Shared` or `FormulaKind::Array` and their
ranges, and `BrtCellMeta` as the cell metadata index. Every cell of a shared formula gets its own
text, decoded at the cell, since the file keeps the tokens once. A formula whose decoding needs
something the reader does not read keeps only its saved result, with a warning saying why: a defined
name left out, table references, other workbooks, Python code stored outside the cell, data tables.
The XLSB function table (`xlsb/ftab.rs`) and the expression printer are this crate's own, apart from
`craft-xls`'s.
## Hostile input
+13 -10
View File
@@ -380,8 +380,8 @@ struct PendingName {
rgce: Vec<u8>,
rgcb: Vec<u8>,
comment: Option<String>,
menu: Option<String>,
description: Option<String>,
help: Option<String>,
}
/// The workbook's defined names, as `.xlsx` has them in `definedNames`: every `BrtName` but the
@@ -435,12 +435,12 @@ fn defined_names(
let mut attrs = vec![];
let mut put = |k: &str, v: String| attrs.push((k.to_string(), v));
// In `CT_DefinedName`'s order.
if let Some(m) = p.menu {
put("customMenu", m);
}
if let Some(d) = p.description {
put("description", d);
}
if let Some(h) = p.help {
put("help", h);
}
let (func, vba, proc) = (p.flags & 0x02 != 0, p.flags & 0x04 != 0, p.flags & 0x08 != 0);
if func {
put("function", "1".into());
@@ -520,14 +520,17 @@ fn link_record(id: u16, payload: &[u8], links: &mut Links, pending: &mut Vec<Pen
let cb = b.u32()? as usize;
let rgcb = b.take(cb)?.to_vec();
let comment = b.string(255, true)?;
// A macro's name (fProc) has four more strings: one unused, its custom menu, its
// description and another unused.
let (menu, description) = if flags & 0x08 != 0 {
// A macro's name (fProc) has four more strings: one unused, its description, its help
// topic and another unused. ([MS-XLSB] calls the second the custom menu and the third
// the description; Excel writes them as `.xlsx`'s `description` and `help`.) Excel
// leaves them out of a VBA function's name (fOB), which ends after its comment.
let vba_without_strings = flags & 0x04 != 0 && b.rest.is_empty();
let (description, help) = if flags & 0x08 != 0 && !vba_without_strings {
b.string(32767, true)?;
let menu = b.string(32767, true)?;
let description = b.string(32767, true)?;
let help = b.string(32767, true)?;
b.string(32767, true)?;
(menu, description)
(description, help)
} else {
(None, None)
};
@@ -536,7 +539,7 @@ fn link_record(id: u16, payload: &[u8], links: &mut Links, pending: &mut Vec<Pen
// A built-in name (fBuiltin) is stored bare; `.xlsx` spells it `_xlnm.Print_Area`, in
// `definedNames` and in formulas alike.
let text = if flags & 0x20 != 0 { format!("_xlnm.{text}") } else { text };
pending.push(PendingName { index: links.names.len(), flags, key, rgce, rgcb, comment, menu, description });
pending.push(PendingName { index: links.names.len(), flags, key, rgce, rgcb, comment, description, help });
links.names.push(Name { text, future: flags & (1 << 17) != 0, scope, read: false });
}
}
+45
View File
@@ -1208,3 +1208,48 @@ fn references_to_macro_sheets_and_spans_over_chart_sheets_are_named() {
assert_eq!(got, [Some("Macro1!$A$1"), Some("Data:Hidden!$A$1"), None]);
assert!(warned(&wb, "references to sheets with no cells"), "{:?}", wb.warnings);
}
#[test]
fn vba_function_names_without_macro_strings_are_read() {
// Excel writes a VBA function a cell calls as a BrtName with fFunc, fOB and
// fProc, no formula, and none of the four strings fProc names otherwise carry. `.xlsm` lists
// no such name; a cell calling the function spells it.
let vba = |text: &str| {
let data = [
&0x0Eu32.to_le_bytes()[..],
&[0],
&u32::MAX.to_le_bytes(),
&wide(text),
&0u32.to_le_bytes(),
&0u32.to_le_bytes(),
&u32::MAX.to_le_bytes(),
]
.concat();
record(39, &data)
};
let mut list = names();
list.push(vba("Twice"));
let twice = [&[0x23u8, 14, 0, 0, 0][..], &[0x1E, 4, 0], &[0x42, 2, 0xFF, 0]].concat();
let data = [row(0), formula_cell(1, &twice, &[]), formula_cell(2, &[0x23, 9, 0, 0, 0], &[])].concat();
let bytes = package(&book_with_names(&list), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES);
let wb = Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap();
assert_eq!(wb.defined_names, xml_names(NAMES_XML));
let book = read(&bytes).unwrap();
assert_eq!([1, 2].map(|c| book.sheets[0].formula(CellRef::new(0, c))), [Some("Twice(4)"), Some("Rate")]);
}
#[test]
fn a_macro_names_description_and_help_topic_are_read_as_excel_writes_them() {
// An XLM function in category 3 with the strings Excel writes after its comment: unused, the
// description, the help topic, unused. [MS-XLSB] labels the middle two the custom menu and the
// description; Excel's `.xlsm` has them as `description` and `help`.
let flags: u32 = 0x02 | 0x08 | (3 << 6);
let mut data = [&flags.to_le_bytes()[..], &[0], &u32::MAX.to_le_bytes(), &wide("FnA")].concat();
let rgce = ref3d_name(0, 0, 0);
data.extend([&(rgce.len() as u32).to_le_bytes()[..], &rgce, &0u32.to_le_bytes(), &u32::MAX.to_le_bytes()].concat());
data.extend([u32::MAX.to_le_bytes().to_vec(), wide("Function A"), wide("!0"), u32::MAX.to_le_bytes().to_vec()].concat());
let bytes = package(&book_with_names(&[record(39, &data)]), &worksheet(&row(0), &[]), &sst(), ROOT, RELS, TYPES);
let wb = Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap();
let xml = r#"<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><definedNames><definedName name="FnA" description="Function A" help="!0" function="1" xlm="1" functionGroupId="3">Data!$A$1</definedName></definedNames></workbook>"#;
assert_eq!(wb.defined_names, xml_names(xml));
}