Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Created April 13, 2022 11:15
Show Gist options
  • Save JohnLBevan/31cf3a9bc31d2f6585f0900eb01e6700 to your computer and use it in GitHub Desktop.
Save JohnLBevan/31cf3a9bc31d2f6585f0900eb01e6700 to your computer and use it in GitHub Desktop.
Fix Excel's Name Manager (workbook contains too many bad references in named ranges) issue
# Thanks to [Reddit](https://www.reddit.com/r/excel/comments/70r89w/need_to_delete_thousands_of_errored_named_ranges/i4huccg)
# for the tip on resolving the name manager issue
# once you've extracted your XLSX file as a zip, find the `workbook.xml` file (should be under the `xl` subfolder)
$wbPath = 'C:\Temp\MyExtractedXlsx\xl\workbook.xml'
# open this XML file / parse it as XML
$wb = [xml](Get-Content -Path $wbPath -encoding UTF8 -Raw)
# find all `definedName` elements which contain the string `#REF!`.
$nodesToDelete = $wb.SelectNodes("/*[local-name()='workbook']/*[local-name()='definedNames']/*[local-name()='definedName' and ./text()[contains(.,'#REF!')]]")
# loop through these found names, removing each from the XML
foreach ($node in $nodesToDelete) {
$node.ParentNode.RemoveChild($node) | Out-Null
}
# Save the XML again, overwriting the original with the updated copy
$wb.Save($wbPath)
# You can now zip the folder again (ensure that the folder's contents are the top level, rather than the zip file
# containing the parent folder too (i.e. the `xl` folder should show when you browse the zip's root directory instead
# of the zip containing the (e.g.) `MyExtractedXlsx` folder.
# Give this zipped copy the XLSX file extension then open it in Excel
# Save the workbook in Excel again (this will clean any entries which have been made redundant by our changes to workbook.xml).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment