在Excel VBA中添加工作表

时间:2018-03-27 19:52:40

标签: excel-vba vba excel

在以下代码中接收错误。 For-Next部分有效,但在wb2.sheets.add行上抛出错误。运行时错误424需要对象。

这曾经有用,不知道发生了什么变化。是否存在语法错误?

'Look for existing sheets named "For Export
'If found, delete existing sheet
For Each S In ThisWorkbook.Sheets

    If S.Name = "For Export" Then
    Application.DisplayAlerts = False
      ' Workbook.Worksheets.Item(S.Name).Delete
    End If
Next S

'Add sheet named "For Export"

Set wb2 = Application.ActiveWorkbook
wb2.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count)).Name = "For Export"

1 个答案:

答案 0 :(得分:0)

'查找名为“For Export”的现有工作表 '如果找到,删除现有工作表 对于每个S在ThisWorkbook.Sheets

If S.Name = "For Export" Then
Application.DisplayAlerts = False
   Workbook.Worksheets.Item(S.Name).Delete
End If
Next S

'Add sheet named "For Export"

Set wb2 = Application.ActiveWorkbook
wb2.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count)).Name = "For Export"

在原始代码中,workbook.delete行已注释掉,在尝试使用相同名称添加工作表时出错。