在第一行搜索特定文字,然后复制整个列

时间:2015-09-03 17:38:51

标签: excel vba search filter rows

我对VBA相当新,而且我在完成看似简单的任务时遇到了很多麻烦。我使用这个网站尝试过很多不同的代码,这是让我最接近我想要的代码,但它并没有返回任何值。以下是我需要它做的前提:

1)搜索特定文字的工作表的整个第一行列(A1代表Z1)"已关闭"

2)如果想要的文字"已关闭"在其中一列中找到,复制该列中的所有值

3)将列中的值粘贴到另一个工作表的J列中(" Source_Workbook")

****编辑**:我希望列数据从列J(10)的第5行之后的下一个空行开始粘贴。我在使用" Offset"时遇到了问题。在这种情况下。此外,我只想粘贴值(保持粘贴数据的页面格式)。

我的问题是,当我尝试执行" Range.PasteSpecial时,此代码一直给我错误。"我希望我有正确的方法。如果我能进一步澄清,请告诉我。

    Dim rng As Range
    Dim cl As Object
    Dim strMatch As String

    strMatch = "Closed" 'Search first row for columns with "Closed"
    Set rng = Target_Workbook2.Sheets(2).Range("A1:Z1")
    For Each cl In rng
        If cl.Value = strMatch Then
            cl.EntireColumn.Copy
            Exit For
            With Source_Workbook2.Sheets(2)
                Sheets(2).Columns("J").Offset(5, 0).PasteSpecial xlPasteValues
            End With
        End If
    Next cl

    Target_Workbook2.Sheets(2).Range("A1:Z1").AutoFilter 1, "*Closed*"

可能更适合过滤?

1 个答案:

答案 0 :(得分:0)

在粘贴Sheet2上的值之前,您将退出for循环 试试这段代码:

Dim rng As Range
Dim cl As Object
Dim strMatch As String

strMatch = "Closed" 'Search first row for columns with "Closed"
Set rng = Target_Workbook2.Sheets(2).Range("A1:Z1")
For Each cl In rng
    If cl.Value = strMatch Then
        cl.EntireColumn.Copy Destination:=Sheets("Sheet2").Columns(10)
        Exit For
    End If
Next cl  

编辑1 :根据评论
这将复制列并从Sheet2上的第5行粘贴它。

Dim rng As range
Dim cl As Object
Dim strMatch As String
Dim lastrow As Long
Dim sh2lastrow As Long      '<--    Newly added
Dim col As Long                 '<--    Newly added
Dim range As range              '<--    Newly added

strMatch = "Closed" 'Search first row for columns with "Closed"
lastrow = Sheets("Sheet1").range("A65536").End(xlUp).Row ' or + 1
sh2lastrow = Sheets("Sheet2").range("J65536").End(xlUp).Row + 4     '<--    Newly added (Because you want to start from row 5)
Set rng = Sheets("Sheet1").range("A1:Z1")
For Each cl In rng
    If cl.Value = strMatch Then
        lastrow = Cells.CurrentRegion.Rows.Count        '<--    (Getting row count of given column)
        col = cl.Column                                     '<--    (Getting column number of given column)
        With Sheets("Sheet1")
            Set range = .range(.Cells(2, col), .Cells(lastrow, col))        '<--    (Setting up the range to copy)
        End With
        range.Copy
        Sheets("Sheet2").Activate       '<--    Newly added
        Sheets("Sheet2").range("J" & sh2lastrow).PasteSpecial xlPasteValues     '<--    (Pasting the copied data)
        sh2lastrow = Sheets("Sheet2").range("J65536").End(xlUp).Row + 1     '<--    (Getting the last row from Sheet2)
        Sheets("Sheet1").Activate
    End If
Next cl