vbahelpneeded15
New Member
- Joined
- Jun 28, 2017
- Messages
- 12
Hi,
I have been trying to set up a VBA code that helps me move rows with the word Sam in column A to the bottom of the sheet (the number of rows with this word changes everyday). I have managed to set up a code that copies the data but it always pastes it in the same row (i.e. row 540) even if it is not the next empty row. I was wondering if I could get some help with it so it pastes in the next empty row instead.
Here's my code:
Sub Step3 ()
Dim r As Range
Dim s As String
Dim firstRowWithS As Long, lastRowWithS As Long, destinationRow As Long
s = "Sam"
destinationRow = 540
For Each r In Sheets("sheetname").Range("A373:A398")
'find first row where we see string s
If r.value = s And r.Offset(-1, 0).value <> s Then
firstRowWithS = r.Row
End If
'find last row where we see string s
If r.value <> s And r.Offset(-1, 0).value = s Then
lastRowWithS = r.Offset(-1, 0).Row
End If
Next
'copy and paste rows to destination
Sheets("sheetname").Range(373 & ":" & 398).Copy Destination:=Sheets("sheetname").Range("A" & destinationRow)
End Sub
Thank you for the help!
I have been trying to set up a VBA code that helps me move rows with the word Sam in column A to the bottom of the sheet (the number of rows with this word changes everyday). I have managed to set up a code that copies the data but it always pastes it in the same row (i.e. row 540) even if it is not the next empty row. I was wondering if I could get some help with it so it pastes in the next empty row instead.
Here's my code:
Sub Step3 ()
Dim r As Range
Dim s As String
Dim firstRowWithS As Long, lastRowWithS As Long, destinationRow As Long
s = "Sam"
destinationRow = 540
For Each r In Sheets("sheetname").Range("A373:A398")
'find first row where we see string s
If r.value = s And r.Offset(-1, 0).value <> s Then
firstRowWithS = r.Row
End If
'find last row where we see string s
If r.value <> s And r.Offset(-1, 0).value = s Then
lastRowWithS = r.Offset(-1, 0).Row
End If
Next
'copy and paste rows to destination
Sheets("sheetname").Range(373 & ":" & 398).Copy Destination:=Sheets("sheetname").Range("A" & destinationRow)
End Sub
Thank you for the help!