'Avoid using activesheet

I have the code below. I get a 400 error when I try to run it.

Sub sbInsertingColumns()

Dim NumRows As Long
Dim Transit As Worksheet

Set Milestone = ActiveWorkbook
Milestone.Activate

Set TransitFile = Workbooks.Open("Y:\File.xlsx")
TransitFile.Sheets("General").Activate
Columns("A:B").Copy
End Sub

The code will work if I change

  Columns("A:B").Copy

to

ActiveSheet.Columns("A:B").Copy

Why is that? I thought I already made the General sheet in the TransitFile active by activating it?



Solution 1:[1]

You can use TransitFile.Sheets("General").Columns("A:B").Copy without having to activate the sheet beforehand. Or you could have used a With to refer to the correct Workbook.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nbayly