mumps
Well-known Member
- Joined
- Apr 11, 2012
- Messages
- 14,151
- Office Version
- 365
- 2010
- Platform
- Windows
I have the following macro that works as expected. It finds only the value of the variable 'response' in column S and copies the appropriate range from the found rows to column C of Sheet2 starting in row 9. Cell C8 of Sheet2 has a header in it.
The following macro (which is what I tried initially) copies the range from every row with data in column S. The 'FindNext' doesn't limit the "find" to only the value of the variable "response".
I can't seem to figure out why the second macro isn't working as expected. Any suggestions would be greatly appreciated.
Code:
Sub CopyData()
Application.ScreenUpdating = False
Dim response As String, sAddr As String
Dim foundResponse As Range
response = InputBox("Please enter the string to find.")
If response = "" Then
MsgBox ("You have not entered a string.")
Exit Sub
End If
Set foundResponse = Sheets("Sheet1").Range("S:S").Find(response, LookIn:=xlValues, lookat:=xlPart)
If Not foundResponse Is Nothing Then
sAddr = foundResponse.Address
Do
Sheets("Sheet1").Range("F" & foundResponse.Row & ":M" & foundResponse.Row).Copy _
Sheets("Sheet2").Cells(Sheets("Sheet2").Rows.Count, "C").End(xlUp).Offset(1, 0)
Set foundResponse = Sheets("Sheet1").Range("S:S").FindNext(foundResponse)
Loop While foundResponse.Address <> sAddr
sAddr = ""
Else
MsgBox ("String not found.")
End If
Application.ScreenUpdating = True
End Sub
Code:
Sub CopyData2()
Application.ScreenUpdating = False
Dim response As String, sAddr As String
Dim lastRow As Long
Dim foundResponse As Range
response = InputBox("Please enter the string to find.")
If response = "" Then
MsgBox ("You have not entered a string.")
Exit Sub
End If
Set foundResponse = Sheets("Sheet1").Range("S:S").Find(response, LookIn:=xlValues, lookat:=xlPart)
If Not foundResponse Is Nothing Then
sAddr = foundResponse.Address
Do
lastRow = Sheets("Sheet2").Columns(3).Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row + 1
Sheets("Sheet1").Range("F" & foundResponse.Row & ":M" & foundResponse.Row).Copy Sheets("Sheet2").Cells(lastRow, 3)
Set foundResponse = Sheets("Sheet1").Range("S:S").FindNext(foundResponse)
Loop While foundResponse.Address <> sAddr
sAddr = ""
Else
MsgBox ("String not found.")
End If
Application.ScreenUpdating = True
End Sub