excel vba在Worksheets.add之后没有执行任何代码

时间:2013-09-11 22:13:53

标签: excel excel-vba vba

我正在尝试在新工作簿中创建一组选项卡,其中的特定名称取自另一个工作簿中的某个范围。在下面的示例中,第一个msgbox被执行但从不第二个。所有选项卡都已创建,但不会重命名。

Sub CreateInstructorSheet(r As Range)
  Dim tabname As String
  tabname = r.Offset(0, 1).Value
  MsgBox tabname + " 1"
  newtab = wb.Worksheets.Add
  MsgBox tabname + " 2"   
  newtab.Name = tabname
End Sub

我也尝试过使用Sheets.add,并在add语句中提供参数。

1 个答案:

答案 0 :(得分:1)

出于某种原因,您尚未声明newtab变量,并且您错过了Set关键字,因为您尝试将newtab设置为工作表对象。您也从未向变量wb声明或赋值。

Sub CreateInstructorSheet(r As Range)

    Dim wb as Workbook
    Dim newtab as Worksheet
    Dim tabname As String

    Set wb = r.Parent.Parent    'The first parent is the range's worksheet
                                'The second parent is the worksheet's workbook

    tabname = r.Offset(0, 1).Value
    MsgBox tabname + " 1"

    Set newtab = wb.Worksheets.Add
    MsgBox tabname + " 2"

    newtab.Name = tabname    'Be very careful here, this can result in an error
                             'if a worksheet already exists with a name
                             'that is the value of tabname
End Sub