0
votes

I would like to modify this macro to paste the copied rows with their original formatting and only their values as the rows being copied have formulas in them. I tried placing PasteSpecial xlPasteValues after Rows(j+6) but that did not do the trick.

    Sub customcopy()
    Dim strsearch As String, lastline As Integer, tocopy As Integer

    strsearch = CStr(InputBox("enter the string to search for"))
    lastline = Range("A65536").End(xlUp).Row
    j = 1

    For i = 1 To lastline
       For Each c In Range("C" & i & ":Z" & i)
          If InStr(c.Text, strsearch) Then
               tocopy = 1
           End If
        Next c
        If tocopy = 1 Then
             Rows(i).Copy Destination:=Sheets("Sheet2").Rows(j + 6)
             j = j + 1
        End If
    tocopy = 0
    Next i

    End Sub
3
you might want to add a line like exit for , just after tocopy=1. because if the copy condition is already met, why bother looping around ? Also, you did not declare J. tocopy,lastline,J as Long wouldn't harm. - Patrick Lepelletier

3 Answers

0
votes

Try:

Sub customcopy()
    Dim strsearch As String, lastline As Long, tocopy As Long
    strsearch = CStr(InputBox("enter the string to search for"))
    lastline = Range("A65536").End(xlUp).Row
    j = 1
    For i = 1 To lastline
       For Each c In Range("C" & i & ":Z" & i)
          If InStr(c.Text, strsearch) Then
               tocopy = 1
           End If
        Next c
        If tocopy = 1 Then
             Rows(i).Copy
             Sheets("Sheet2").Rows(j + 6).PasteSpecial (xlValues)
             Sheets("Sheet2").Rows(j + 6).PasteSpecial (xlFormats)
             j = j + 1
        End If
        tocopy = 0
    Next i
End Sub
0
votes

Try this

Sub customcopy()
Dim strsearch As String, lastline As Integer, tocopy As Integer

strsearch = CStr(InputBox("enter the string to search for"))
lastline = Range("A65536").End(xlUp).Row
j = 1

For i = 1 To lastline
   For Each c In Range("a" & i & ":a" & i)
      If InStr(c.Text, strsearch) Then
           tocopy = 1

       End If
    Next c
    If tocopy = 1 Then
         Rows(i).Copy
         Sheets("Sheet2").Rows(j + 6).PasteSpecial Paste:=xlPasteValues
         Sheets("Sheet2").Rows(j + 6).PasteSpecial Paste:=xlPasteFormats

         j = j + 1
    End If
tocopy = 0
Next i

End Sub
0
votes

I'm sure there are certainly better ways to keep the formatting AND drop in only the values, but one quick solution might be to first paste everything (that way you've got the formatting), THEN paste just the values:

Rows(i).Copy Destination:=Sheets("Sheet2").Rows(j + 6)
Sheets("Sheet2").Rows(j + 6).PasteSpecial Paste:=xlPasteValues