Andrei Ion
Andrei Ion

Reputation: 1827

Error with a Range selection

I have some problems with a piece of code. I get an error when it has to select a range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim valrand As Long
If Intersect(Target, ActiveCell) = "Insert line" Then
valrand = ActiveCell.Row
    If Worksheets("IR").Cells(valrand, 18).Value <> 5 Then
        Sheets("Format").Select
        MsgBox ("Format")
        Range("A13:N13").Select 'here's the error
        Selection.Copy

        Sheets("IR").Select
        Range("A" & valrand + 2 + Worksheets("IR").Cells(12, 18) & ":N" & valrand + 2 + Worksheets("IR").Cells(12, 18)).Select
        Selection.Insert Shift:=xlDown

        Range("A38:N38").Select
        Application.CutCopyMode = False
        Selection.Delete Shift:=xlUp

        Range("A5").Select
        contor = Worksheets("IR").Cells(12, 18).Value + 1
        Worksheets("IR").Cells(12, 18).Value = contor
    End If
End If
End Sub

Where I put the commet "here's the error" it gives me "Select method of Range class failed" What am I doing wrong? Usually this piece of code worked before I added in the SelectionChange code block. Thanks!

Upvotes: 2

Views: 2024

Answers (1)

brettdj
brettdj

Reputation: 55672

You should look at avoiding Select when using Sheet code (best to avoid it altogether, more later on this) and use something like this instead

Application.Goto Sheets("Format").Range("A13:N13")

(I had tried fully qualifying the reference but this only worked if I used

   Sheets("Format").Select
   Sheets("Format").Range("A13:N13").Select

which is clearly overkill)

While that solves you immediate issue you should look at consolidating your code, for example

  1. Disabling Events so that other sheet events dont fire while your Select is running
  2. Removing any Select statements

This is an example of what may work better (now with no sheet activation)

 Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim lngRand As Long
    Dim rng1 As Range
    Set ws1 = Sheets("Format")
    Set ws2 = Sheets("IR")
    If Intersect(Target, ActiveCell) = "Insert line" Then
        lngRand = ActiveCell.Row
        If ws2.Cells(lngRand, 18).Value <> 5 Then
            Application.EnableEvents = False
            Set rng1 = Range("A" & lngRand + 2 + ws2.Cells(12, 18))
            'extend rng1 from column A to colum N
            Set rng1 = rng1.Resize(rng1.Rows.Count, 14)
            ws2.Range(rng1.Address).Insert xlDown
            'copy Format to IR
            ws1.Range("A13:N13").Copy ws2.Range(rng1.Address)
            'Update Format
            ws2.Range("A38:N38").Delete Shift:=xlUp
            ws2.Cells(12, 18).Value = ws2.Cells(12, 18).Value + 1
            Application.EnableEvents = True
        End If
    End If
End Sub

Upvotes: 6

Related Questions