复制和粘贴工作表名称到另一个不活动的工作表,而不使用select/激活
我试图通过重写它不使用select来加速我的代码。
我有三个选项卡,我希望将选项卡名称粘贴到显示在相应选项卡中的数据旁边,而不必select选项卡。
但是,我发现当我运行代码时,例如在工作表1上,它适用于工作表1,但是当它试图做同样的工作表2失败,错误“运行时错误'1004':Application-定义的或对象定义的错误“。
请看下面我的代码。
Sub Create_Reports_NEWWWW() Application.ScreenUpdating = False Dim wb As Workbook Dim LastRow As Integer Dim LastColumn As Integer Set wb = ActiveWorkbook 'copy sheet name to right of raw data on each sheet LastRow = wb.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row LastColumn = wb.Sheets(1).Cells(4, Columns.Count).End(xlToLeft).Column wb.Sheets(1).Range(Cells(4, LastColumn + 1), Cells(LastRow, LastColumn + 1)) = wb.Sheets(1).Name LastRow = wb.Sheets(2).Cells(Rows.Count, 1).End(xlUp).Row LastColumn = wb.Sheets(2).Cells(4, Columns.Count).End(xlToLeft).Column wb.Sheets(2).Range(Cells(4, LastColumn + 1), Cells(LastRow, LastColumn + 1)) = wb.Sheets(2).Name LastRow = wb.Sheets(3).Cells(Rows.Count, 1).End(xlUp).Row LastColumn = wb.Sheets(3).Cells(4, Columns.Count).End(xlToLeft).Column wb.Sheets(3).Range(Cells(4, LastColumn + 1), Cells(LastRow, LastColumn + 1)) = wb.Sheets(3).Name
这里是:
Sub Create_Reports_NEWWWW() Application.ScreenUpdating = False Dim wb As Workbook Dim lastRow As Integer Dim lastColumn As Integer Set wb = ActiveWorkbook With wb.Sheets(1) 'copy sheet name to right of raw data on each sheet lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row lastColumn = .Cells(4, .Columns.Count).End(xlToLeft).Column .Range(.Cells(4, lastColumn + 1), .Cells(lastRow, lastColumn + 1)) = .Name End With With wb.Sheets(2) lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row lastColumn = .Cells(4, .Columns.Count).End(xlToLeft).Column .Range(.Cells(4, lastColumn + 1), .Cells(lastRow, lastColumn + 1)) = .Name End With With wb.Sheets(3) lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row lastColumn = .Cells(4, .Columns.Count).End(xlToLeft).Column .Range(.Cells(4, lastColumn + 1), .Cells(lastRow, lastColumn + 1)) = .Name End With End Sub
您不能在非活动的工作表上使用Cells
。 您需要使用wb.Sheets(2).Cells(x,y)
这个代码中的With
块就是为了节省空间。 每个.Range
或.Cells
指的是例如wb.Sheets(1)
,可以看作是wb.Sheets(1).Cells(x,y)..
顺便说一句:停止使用Select
和Activate
是非常好的,你也应该避免ActiveWorkbook
或ActiveWorksheet
。 这是非常不可靠的,你永远不会知道用户会做什么。 ;)
HTH