Thursday, July 30, 2009

Getting "runtime error 1004 select method of range class failed" w/Excel Macro?

I built a macro in Excel that basically does the following - goes to a selected sheet, removes some rows and columns for formatting, paste the remaining values and then copies them into another sheet within the same book.





When I run the macro with the cntl+h short cut, it works without a problem.





When I assign the macro to a click button thats when the 1004 error shows up all over the place. Here is the crux of the code that's problematic





Sheets("HV INPUT").Activate


Range("A:A,C:C,D:D,F:F").Select


Range("F1").Activate


Selection.Delete Shift:=xlToLeft


Rows("1:4").Select


Range("A4").Activate


Selection.Delete Shift:=xlUp


Columns("A:B").Select


Selection.Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlNo, _


OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _


DataOption1:=xlSortNormal


Selection.Copy


Sheets("HV").Select


Range("A1").Select


...


Why would the short cut key work but not with the button? HELP!!!

Getting "runtime error 1004 select method of range class failed" w/Excel Macro?
The 1004 Error message is a catch-all object defined error message. It means your error doesn't fit the other error message types.





The very first thing I'd look at is to see if you've changed any of the worksheet names or deleted any of the worksheets. From what I see, that seems like the only thing it might be. You might also include what line the error handler is hi-lighting so it gives a little more clue as to what line is might be causing the problem.





I'd recommend referencing the worksheet code names instead of the sheet names. The code name can't be changed by the user unless they go into the Visual Basic Editor screen.





One other thing, you have way to many Select and Activate statements. Your code could be greatly simplified. Note that the space followed by an underscore at the end of a line denotes a line continuation in VB. For example:





Sheets("HV INPUT").Activate


Range("A:A,C:C,D:D,F:F").Delete _


Shift:=xlToLeft


Rows("1:4").Delete Shift:=xlUp


Columns("A:B").Sort Key1:=Range("A1"), _


Order1:=xlAscending, Header:=xlNo, _


OrderCustom:=1, MatchCase:=False, _


Orientation:=xlTopToBottom, _


DataOption1:=xlSortNormal


Columns("A:B").Copy


Sheets("HV").Select


Range("A1").Select


No comments:

Post a Comment