我试图通过重写不使用select来加速我的代码。
我有三个标签,我想将标签名称粘贴到相应标签中显示的数据旁边,而不选择标签。
然而,我发现当我运行代码时,例如在表1中,它适用于表1,但是当它试图对表2执行相同操作时,它会失败并显示错误“运行时错误'1004' :应用程序定义或对象定义的错误。“
请参阅下面的代码。
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
答案 0 :(得分:2)
这是:
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
非常好,您还应该避免使用{{1}}或{{1}}。它非常不可靠,你永远不会知道用户会做什么。 ;)
HTH