Excel vba使用表格在新工作表中设置样式

时间:2016-08-14 15:49:00

标签: excel-vba stylesheet vba excel

如何纠正此代码? 我会在新工作表中设置样式,但是这段代码会产生1004错误

Sub test()
Sheets.Add.Name = "new"
ActiveSheet.Range(ActiveSheet.Cells(1, 1), ActiveSheet.Cells(3, 3)) = "test"
ActiveSheet.ListObjects.Add(xlSrcRange, Range(ActiveSheet.Cells(1, 1), ActiveSheet.Cells(3, 3)), , xlYes, , "TableStyleMedium7").Name = "sk"
End Sub

1 个答案:

答案 0 :(得分:0)

我可以模拟您的错误的唯一原因是,您的工作簿中已经有一个名为“ new ”的工作表。如果是这种情况,请尝试以下代码:

Sub test()

Dim sht                     As Worksheet
Dim shtNewExists            As Boolean

shtNewExists = False

' loop through workbook sheet to search if "new" already exists
For Each sht In ThisWorkbook.Sheets
    If sht.Name = "new" Then
        shtNewExists = True
    End If
Next sht

' is sheet "new" doesn't exist then create one
If Not shtNewExists Then Sheets.Add.Name = "new"

Set sht = ThisWorkbook.Sheets("new")

sht.Range(sht.Cells(1, 1), sht.Cells(3, 3)) = "test"
sht.ListObjects.Add(xlSrcRange, sht.Range(sht.Cells(1, 1), sht.Cells(3, 3)), , xlYes, , "TableStyleMedium7").Name = "sk"

End Sub