VBA只粘贴值而不是粘贴每个东西

时间:2014-08-03 17:50:00

标签: excel vba excel-vba xlsm

我正在开发一个小项目,要求我通过一列搜索一个单词,然后将包含我单词的整行复制到另一张表中。 这是我的代码和我到目前为止所拥有的:

    Sub SearchForString2()

    Dim LSearchRow As Integer
    Dim LCopyToRow As Integer

    On Error GoTo Err_Execute

    'Start search in row 4
    LSearchRow = 10

    'Start copying data to row 2 in Sheet2 (row counter variable)
    LCopyToRow = 3

    While Len(Range("J" & CStr(LSearchRow)).Value) > 0

        'If value in column E = "Mail Box", copy entire row to Sheet2
        If Range("M" & CStr(LSearchRow)).Value = "NEW" Then

            'Select row in Sheet1 to copy
            Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
            Selection.Copy

            'Paste row into Sheet2 in next row
            Sheets("New2").Select
            Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
            ActiveSheet.Paste

            'Move counter to next row
            LCopyToRow = LCopyToRow + 1

            'Go back to Sheet1 to continue searching
            Sheets("Old").Select

        End If

        LSearchRow = LSearchRow + 1

    Wend

    'Position on cell A3
    Application.CutCopyMode = False
    Range("A3").Select

    MsgBox "OK!"

    Exit Sub

Err_Execute:
    MsgBox "An error occurred."

End Sub

我希望代码只粘贴所选行的值而不使用格式或公式。有什么建议?提前谢谢。

2 个答案:

答案 0 :(得分:2)

试试这个:

While Len(Range("J" & CStr(LSearchRow)).Value) > 0

    'If value in column E = "Mail Box", copy entire row to Sheet2
    If Range("M" & CStr(LSearchRow)).Value = "NEW" Then

        Sheets("New2").Rows(LCopyToRow).Value = Rows(LSearchRow).Value

        'Move counter to next row
        LCopyToRow = LCopyToRow + 1

    End If

    LSearchRow = LSearchRow + 1
Wend

答案 1 :(得分:1)

您可以使用PasteSpecial而不是使用Paste,并指定xlPasteValues,它只会粘贴值而忽略其他所有内容。

但请注意,PasteSpecialRange对象的方法,而不是Worksheet

这些SO问题在您的案例中也非常相关: