简体   繁体   中英

Copy cells in column M that start with “xx” and paste them into another sheet

I am trying to make a button that will find all cells in column H starting with rm and copy them from one sheet to another.

sheet2 column M would go to sheet 1 column A

Dim i As Variant
Dim rng As Range

Set x = Range("m" & i)

If Left(rng.Value, 2) = "rm" Then
For Each i In x
Worksheets("scope sheet").Range("A5").Value = Range(i)
Next i
End If

this gives an error "method 'range' of Object '_global' failed."

if i add a With statement i get "subscript out of range."

does anyone know a work around.

You need to use Left(Range, 2) and make some changes to your loop structure. The code is currently looping from the second row down to the last used row ( lr )

Option Explicit

Sub test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet2") '<-- UPDATE SHEET
Dim i As Long, LR As Long

LR = ws.Range("M" & ws.Rows.Count).End(xlUp).Row

For i = 2 To LR
    If Left(ws.Range("M" & i), 2) = "rm" Then
        ThisWorkbook.Sheets("Sheet1").Range("A" & i).Value = ws.Range("M" & i).Value
    End If
Next i

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM