我正在尝试将工作簿中的数据复制到新工作簿并重命名工作表。代码在2013年运行良好,但相同的代码在Windows 10 2016中引发错误。
Below is the sample code (made changes)
Sub test()
Range("a" & Rows.Count).End(xlUp).Offset(1, 0) = "This workbook"
Application.ScreenUpdating = False
Set newwb = Workbooks.Add
Worksheets.Add
Worksheets.Add
For i = 0 To 50
newwb.Activate
Range("a" & Rows.Count).End(xlUp).Offset(1, 0) = "activeworkbook workbook"
ActiveWorkbook.Sheets(1).Name = "test"
newwb.Activate '--> I don't need to add this code but just to check if it works and still the same issue.
ActiveWorkbook.Sheets(2).Name = "test2"
ActiveWorkbook.Sheets(3).Name = "test3"
ThisWorkbook.Activate
Range("a" & Rows.Count).End(xlUp).Offset(1, 0) = "This workbook"
Next
End Sub
Can you say why it is throwing the error?
Code works perfectly fine in windows 7 excel 2013 but same code throws error in 2016.
It would be great if anyone can help me with this issue.
答案 0 :(得分:0)
使用直接参考并避免使用ActiveWorkbook。你也应该在使用之前对变量进行Dim变换......
Sub test()
On Error GoTo ExitSub
Application.ScreenUpdating = False
Dim newwb As Workbook: Set newwb = Workbooks.Add
newwb.Worksheets.Add
newwb.Worksheets.Add
Dim i As Long
ThisWorkbook.Range("A" & Rows.Count).End(xlUp).Offset(1, 0) = "This workbook"
With newwb
For i = 0 To 50
.Range("a" & Rows.Count).End(xlUp).Offset(1, 0) = "activeworkbook workbook"
.Sheets(1).Name = "test"
.Sheets(2).Name = "test2"
.Sheets(3).Name = "test3"
ThisWorkbook.Range("a" & Rows.Count).End(xlUp).Offset(1, 0) = "This workbook"
Next i
End With
ExitSub:
Application.ScreenUpdating = True
End Sub