2010-09-10 586 views
51

當我嘗試使用紅寶石設置一個稍長的工作表名稱,並用下面的代碼WIN32OLE:Excel工作表名稱長度是否有限制?

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 ,但它抱怨工作表名稱太長。我在this related answer中提到了Excel 2007 specifications and limits,我沒有發現它提到了任何這樣的限制。 (試圖重新命名工作表手動表明可能存在這樣的限制,但是)

是否有限制,並且它是一個硬限制或一個可以通過改變Excel的配置改變?

+0

https://excelribbon.tips.net/T013175_Using_Very_Long_Worksheet_Tab_Names.html可能會引起興趣,但不是最近的。 – pnuts 2018-02-25 17:21:04

回答

80

文件格式將允許最多255個字符的工作表的名稱,但如果Excel UI不希望你超過31個字符,不要試圖超越31應用程序的完整的怪異無證限制和怪癖,和給它提供規範內但不在測試者測試範圍內的文件通常會導致非常奇怪的行爲。 (個人最喜歡的例子:在Excel 97風格的字符串表文件中使用Excel 4.0字節碼作爲if()函數,禁用了Excel 97中粗體的工具欄按鈕。)

+36

31個字符的限制是*不可接受*。 – 2012-10-25 13:00:57

+18

因此寫一個更好的電子表格:) – mjfgates 2012-10-27 13:14:21

+1

TERRIFIC bug! 想換一個嗎? ;-) – 2013-03-20 14:11:27

7

在Excel中手動重命名工作表,你打的31個字符的限制,所以我認爲這是一個硬性限制。

1

我的解決方案是使用短暱稱(小於31個字符),然後在寫單元中的整個名字0

+3

這不是一個真正的答案,作爲評論會更好。 – 2015-11-10 19:41:51

+2

那麼沒有解決方案。所以這個解決方案是我們最接近的解決方案。你也可以對另外兩個沒有提供解決方案或建議的評論說。 – nikon0iT 2016-01-05 20:48:45

1

我使用下面的VBA代碼其中文件名是包含我想要的文件名的字符串,和功能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