2009-11-09 29 views
1
創建表格樣式

我使用下面的函數來創建一個TableStyle:錯誤而在Excel

Public Function CreateTableStyle() 
ActiveWorkbook.Unprotect 

Dim objTS As TableStyle 
On Error Resume Next 
Set objTS = ActiveWorkbook.TableStyles("MyTableStyle") 
On Error GoTo err_CreateTableStyle 
If Not objTS Is Nothing Then 
    Exit Function 
End If 

Set objTS = ActiveWorkbook.TableStyles.Add("MyTableStyle") 
With ActiveWorkbook.TableStyles("MyTableStyle") 
    .ShowAsAvailablePivotTableStyle = True 
    .ShowAsAvailableTableStyle = False 
End With 
With ActiveWorkbook.TableStyles("MyTableStyle").TableStyleElements(_ 
    xlHeaderRow).Font 
    .FontStyle = "Bold" 
    .TintAndShade = 0 
    .ThemeColor = xlThemeColorDark1 
End With 
With ActiveWorkbook.TableStyles("MyTableStyle").TableStyleElements(_ 
    xlHeaderRow).Interior 
    .ThemeColor = xlThemeColorLight2 
    .TintAndShade = -0.249946592608417 
End With 
With ActiveWorkbook.TableStyles("MyTableStyle").TableStyleElements(_ 
    xlTotalRow).Font 
    .FontStyle = "Bold" 
    .TintAndShade = 0 
    .ThemeColor = xlThemeColorDark1 
End With 
With ActiveWorkbook.TableStyles("MyTableStyle").TableStyleElements(_ 
    xlTotalRow).Interior 
    .ThemeColor = xlThemeColorLight2 
    .TintAndShade = -0.249946592608417 
End With 
ActiveWorkbook.TableStyles("MyTableStyle").TableStyleElements(_ 
    xlSubtotalRow1).Font.FontStyle = "Bold" 
With ActiveWorkbook.TableStyles("MyTableStyle").TableStyleElements(_ 
    xlSubtotalRow1).Interior 
    .Color = 16764828 
    .TintAndShade = 0 
End With 
ActiveWorkbook.TableStyles("MyTableStyle").TableStyleElements(_ 
    xlSubtotalRow2).Font.FontStyle = "Bold" 
With ActiveWorkbook.TableStyles("MyTableStyle").TableStyleElements(_ 
    xlSubtotalRow2).Interior 
    .Color = 16777164 
    .TintAndShade = 0 
End With 

ActiveWorkbook.Protect 

Exit Function 

err_CreateTableStyle: 
    Call Common.ErrRaise(Erl, "Common", "CreateTableStyle", "CreateTableStyle") 

End Function 

在下面的一行:

With ActiveWorkbook.TableStyles("MyTableStyle").TableStyleElements(_ xlHeaderRow).Font .FontStyle = "Bold"

我得到一個錯誤:

運行時錯誤'1004' 無法設置Font類的FontStyle屬性。

有人可以找出問題嗎?我無法弄清爲什麼它不讓我設置財產。

+0

的代碼工作。我不確定爲什麼它不適用於該特定行。你可以刪除錯誤處理程序(錯誤恢復下一個和錯誤goto ....)並查看它失敗的地方? – shahkalpesh 2009-11-09 06:35:41

+0

在相同的語句中失敗。我正試圖通過XLA運行此代碼。它通過XLA工作嗎?它通過一個宏而不是XLA來工作。 – 2009-11-09 08:20:23

+0

如何設置Bold屬性呢?那樣有用嗎? – shahkalpesh 2009-11-09 08:39:51

回答

0

XLA的行爲可能不同一段時間....它們被加載/時將啓動Excel,打開任何表(即使是空的)前執行,因此,一個XLA asuming本打開的書會失敗

如果這代碼旨在設置一些「默認格式」...

...我寧願設置格式並將整個工作表保存爲表或工作簿模板(XLT),然後使用該模板創建新文件,

...或者 - 再次在模板中存儲上述代碼,並從事件宏(如Workbook_NewSheet()或Workbook_Open())調用它,