Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Time Error '1004': Select method of Range Class failed using ThisWorkbook

Tags:

excel

vba

During the process of running a script if I manually remove focus from the Workbook containing the macro I get the error quoted. If I don't click on anything it works without issue. Script errors out only when I'm trying to place selection back into A1 from the "Input" sheet. Break point is on following line:

ThisWorkbook.Sheets("Input").Range("A1").Select

If I debug and place focus back on macro Worksheet the script completes without issue. Previous line:

ThisWorkbook.Sheets("Input").Cells.Delete

runs without error so I'm guessing its the range that is falling out of scope but don't quite understand why as it should be defined by the previous scope notations. Can someone explain why that line is falling out of scope? Shouldn't the ThisWorkbook define fairly explicitly the Workbook that my code is referencing? Any guidance is greatly appreciated.

like image 605
nbayly Avatar asked Mar 22 '16 21:03

nbayly


1 Answers

It doesn't have anything to do with the reference to ThisWorkbook at all. You simply can't Select a Range in an object that isn't active. Consider this code, which exhibits the same error:

Private Sub OneOhOhFour()

    'Executing with Book1.xlsm active and Book2.xlsx open.
    Dim wb As Workbook
    Set wb = Application.Workbooks("Book2.xlsx")
    Debug.Print ThisWorkbook.Name
    'Outputs 'Book1.xlsm' to Immediate window.
    wb.Sheets("Sheet1").Range("A1").Select   'Error 1004

End Sub 

Same thing with Worksheets:

Private Sub OneOhOhFourVTwo()
    'Starting on anywhere but Sheet2 gives an error.
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet2")
    ws.Range("A1").Select  'Error 1004.
End Sub

The simple solution is to Activate the object before you Select within it:

Private Sub NoOneOhOhFour()

    Dim wb As Workbook
    Set wb = Application.Workbooks("Book2.xlsx")
    wb.Activate
    wb.Sheets("Sheet1").Range("A1").Select  'No error.

End Sub

Even better is using references and trying to avoid using the Selection and Active* objects entirely.

like image 85
Comintern Avatar answered Nov 08 '22 06:11

Comintern