zl程序教程

您现在的位置是:首页 >  工具

当前栏目

Excel:文件打开后已设置的单元格格式全部消失

Excel文件 设置 打开 格式 全部 消失 单元格
2023-06-13 09:12:58 时间

文章背景: 根据工作的需要,早期内部根据不同需求设置了很多模板文件,都是xls格式,而目前电脑上使用的软件是office365。最近发现,采用这些模板文件(xls格式),拷贝完数据并保存后,下次再打开时,已设置好的单元格格式全部消失,类似记事本上的数据。一开始只是个别文件有问题,后来这样的问题文件逐渐增多。

1 原因分析

经研究发现,最可能是原因是单元格格式超出限制而无法保存。那么这个限制是多少呢?Excel 2003版本的文件能支持的单元格格式个数是4,000;Excel 2007及以后版本能支持的单元格格式个数是64,000

When you open a file, all the formatting is missing. This problem occurs when the workbook contains more than approximately 4,000 different combinations of cell formats in Excel 2003 or 64,000 different combinations in Excel 2007 and later versions. A combination is defined as a unique set of formatting elements that are applied to a cell. A combination includes all font formatting (for example: typeface, font size, italic, bold, and underline), borders (for example: location, weight, and color), cell patterns, number formatting, alignment, and cell protection.

In Excel, style counts may increase when you copy between workbooks because custom styles are copied.

A workbook that has more than 4,000 styles may open in Excel 2007 and later versions because of the increased limitation for formatting. However, this can cause an error in Excel 2003.

回到问题的开头,早期做好的模板文件都是xls格式,工作簿内有多张worksheet,由于不断地往里面添加内容,工作簿间相互拷贝数据,随着记录的单元格格式的增多,逐渐达到了4000的上限,因此,出现了单元格格式无法保存的现象。点击问题文件的Cell Styles,确实发现多出来了很多很多的样式。

2 解决思路

(1)对于已存在的问题文件(拷贝好数据的文件),目前没有更好的恢复单元格格式的方法,丢失的就再也找不回来了,因为在保存的时候已经被过滤掉了。

(2)针对模板文件,如果worksheet个数只有一到两个,建议将数据拷贝到新工作簿中,再重新设置格式,当然首选xlsx或xlsm文件,毕竟可以储存64000个格式。

(3)针对模板文件,如果worksheet个数较多,不方便拷贝到新工作簿中,那只能删除已存在的非内置单元格格式,而这将近4000个的单元格格式,显然没办法手动删除,只能通过VBA代码来解决。

Option Explicit

Sub ClearCustomStyle()

    '清除非内置的单元格格式
    Dim Sty As Style
    
    For Each Sty In ActiveWorkbook.Styles
    
       If Not Sty.BuiltIn Then Sty.Delete
       
    Next
    
End Sub

参考资料:

[1] 为什么Excel文件打开后全部格式都…(https://blog.csdn.net/excelstudio/article/details/18262367)

[2] You receive a "Too many different cell formats" error message in Excel (https://docs.microsoft.com/en-us/office/troubleshoot/excel/too-many-different-cell-formats-in-excel)