0

我正在尝试在新工作簿中创建一堆选项卡,其特定名称取自另一个工作簿中的某个范围。在下面的示例中,第一个 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 语句中提供参数。

4

1 回答 1

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
于 2013-09-11T22:23:44.477 回答