I'm setting a range which I've called SCT_table
which would cover the table on worksheet one called SCT_ws
, if this is not the active worksheet I get the error Run-time error '1004'
and the Set SCT_table
line is highlighted when I press debug. Now if I select this worksheet before setting the range (forcing it to be the active worksheet) it runs without a problem. Below is the code:
Sub Join_Suitable_changes()
Application.ScreenUpdating = False
Dim SCT_ws As Worksheet
Dim SCT_num_rows, SCT_num_cols, score_col As Long
Dim SCT_table As Range
Set SCT_ws = ActiveWorkbook.Worksheets(1)
score_col = 7
SCT_num_rows = SCT_ws.Range("A" & Rows.Count).End(xlUp).Row
SCT_num_cols = SCT_ws.Cells(1, Columns.Count).End(xlToLeft).Column
'SCT_ws.Select 'Works with this uncommented
Set SCT_table = SCT_ws.Range("A1", Cells(SCT_num_rows, SCT_num_cols))
'This causes a problem
SCT_table.Sort Key1:=Cells(1, score_col), Order1:=xlAscending, Header:=xlYes
'Sorts the table on column 7
Application.ScreenUpdating = True
End Sub
I tried this question Cannot set a range variable without selecting sheet first which suggested using with, and when I changed the Set part of my code to the following:
With SCT_ws
Set SCT_table = .Range("A1", .Cells(SCT_num_rows, SCT_num_cols))
End With
I no longer need to select the WS in order to set the range (yay), however, I still need to select the WS in order for the Sort
to work. So unfortunately this has not stopped the use of Select.
I'd appreciate any explanation as to why this is the case and how I can avoid the use of Select.