Excel vba 在新 sheet 中设置样式 table
Excel vba set style in new sheet with a table
如何纠正此代码?
我会在 new sheet 中设置样式,但对于此代码给出 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
我可以模拟你的错误的唯一原因是,如果你已经有一个名为“new”的 sheet在你的工作簿中。如果是这种情况,请尝试以下代码:
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
如何纠正此代码? 我会在 new sheet 中设置样式,但对于此代码给出 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
我可以模拟你的错误的唯一原因是,如果你已经有一个名为“new”的 sheet在你的工作簿中。如果是这种情况,请尝试以下代码:
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