Excel工作表名称长度是否有限制?

当我尝试使用以下代码使用ruby和win32ole设置较长的工作表名称时:

require "win32ole" excel = WIN32OLE.new('Excel.Application') excel.Visible = 1 puts excel.version workbook = excel.Workbooks.Add worksheet1 = workbook.Worksheets.Add worksheet1.Name = "Pseudopseudohypoparathyroidism" #Length 30, fine worksheet2 = workbook.Worksheets.Add worksheet2.Name = "Supercalifragilisticexpialidocious" #Length 34, not fine 

我得到以下内容:

 12.0 -:9:in `method_missing': (in setting property `Name': ) (WIN32OLERuntimeError) OLE error code:800A03EC in Microsoft Office Excel You typed an invalid name for a sheet or chart. Make sure that: The name that you type does not exceed 31 characters. The name does not contain any of the following characters: : \ / ? * [ or ] You did not leave the name blank. HRESULT error code:0x80020009 Exception occurred. from -:9:in `<main>' 

版本12.0表明我正在运行Excel 2007,但是抱怨工作表名称太长。 我看了一下在这个相关的答案中提到的Excel 2007规范和限制 ,我没有发现它提到任何这样的限制。 (尝试手动重命名工作表表明可能有这样的限制,但是)

是否有限制,是一个硬限制还是可以通过更改Excel的configuration进行更改?

文件格式将允许最多255个字符的工作表名称,但是如果Excel用户界面不希望超过31个字符,请不要超越31个。应用程序中充满了奇怪的未logging的限制和怪癖,并为其提供文件在规范范围内,但不在testing人员testing的范围内,通常会导致非常奇怪的行为。 (个人最喜欢的例子:在Excel 97风格的string表文件中使用Excel 4.0字节码作为if()函数,禁用了Excel 97中粗体的工具栏button。)

在Excel中手动重命名工作表,你达到了31个字符的限制,所以我build议这是一个硬性限制。

我的解决scheme是使用一个简短的昵称(less于31个字符),然后写在单元格0的全名。

我使用下面的vba代码,其中filename是一个包含我想要的文件名的string,函数RemoveSpecialCharactersAndTruncate定义如下:

 worksheet1.Name = RemoveSpecialCharactersAndTruncate(filename) 'Function to remove special characters from file before saving Private Function RemoveSpecialCharactersAndTruncate$(ByVal FormattedString$) Dim IllegalCharacterSet$ Dim i As Integer 'Set of illegal characters IllegalCharacterSet$ = "*." & Chr(34) & "//\[]:;|=," 'Iterate through illegal characters and replace any instances For i = 1 To Len(IllegalCharacterSet) - 1 FormattedString$ = Replace(FormattedString$, Mid(IllegalCharacterSet, i, 1), "") Next 'Return the value capped at 31 characters (Excel limit) RemoveSpecialCharactersAndTruncate$ = Left(FormattedString$, _ Application.WorksheetFunction.Min(Len(FormattedString), 31)) End Function