2016-07-29 72 views
1

我想通過它沒有使用選擇重寫,以加快我的代碼。複製和粘貼工作表名稱到另一個工作表是不活動,不使用選擇/激活

我有三個標籤,我想粘貼旁邊出現在各個選項卡中的數據卡名稱,而沒有選擇的選項卡。

但是,我發現當我運行代碼時,例如在工作表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 

回答

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)..

而且順便說一句:這是非常好的停止使用SelectActivate,你也應該避免ActiveWorkbookActiveWorksheet。這是非常不可靠的,你永遠不會知道用戶會做什麼。 ;)

HTH

+1

++你是對的。我還建議在行和列之前添加DOTS。 –

+0

對,謝謝。編輯它們。 –

+0

因爲我知道。 :P你想讓我解釋一下嗎? ;) –

相關問題