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