如果列中有文本匹配项并移至特定工作表,如何选择整列?

时间:2019-02-15 20:30:03

标签: excel vba

我有一个excel电子表格,每次都会生成不同的列名,但是具有相同的起始词。

例如,我可以有一列名为“ Key”的列,在2至3列之后,列的名称将为key3,key29,同样,我有另一个单词称为value,然后在某些列value6之后有value1,value2, value7等

我要做的是在工作表Rows(“ 1:1”)中搜索列名。如果文本与我分配的值匹配,请选择并选择整列,最后将其复制到单独的工作表中。 / p>

到目前为止,这是我尝试过的。

Rows("1:1").Select 'Selecting the columns row
' Finding values with name i want to look for
Selection.Find(What:="key", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate.Select

2 个答案:

答案 0 :(得分:0)

Option Explicit

Sub test()

    Dim cell As Range, rng As Range
    Dim SearchString As String
    Dim LastColumn As Long

    SearchString = "Test"

    With ThisWorkbook.Worksheets("Sheet1")
        Set rng = .Rows("1")

        For Each cell In rng.Cells

            If InStr(1, cell.Value, SearchString) > 0 Then

                LastColumn = ThisWorkbook.Worksheets("Sheet2").Cells(1, ThisWorkbook.Worksheets("Sheet2").Columns.Count).End(xlToLeft).Column
                .Columns(cell.Column).Copy ThisWorkbook.Worksheets("Sheet2").Columns(LastColumn + 1)
            End If

        Next

    End With

End Sub

答案 1 :(得分:0)

下面的代码将为您提供一个良好的开端。根据需要调整任何工作表,单元格和范围引用。如果您不熟悉任何方法,那么我使用的每种方法还有很多资源。

With Worksheets("Sheet1")' change as needed

    Dim lastRow as Long
    lastRow = .Cells(.Rows.Count,1).End(xlUp).Row 'change column as needed

    Dim headers as Range
    Set headers = .Range("A1",.Cells(1,.Columns.Count).End(xlToLeft))

    Dim findIt as String
    findIt = "key"

    Dim cel as Range
    For each cel in headers
        If cel.Text like "*key*" Then 
            .Range(cel,.Cells(lastRow, cel.Column)).Copy worksheets("sheet2").Cells(1,cel.Column) 'change sheet and column as needed
        End if
   Next

End With