用于搜索行标题的VBA代码,并选择该标题下的整个范围

时间:2017-04-12 15:45:10

标签: excel vba excel-vba

我对VBA非常陌生,我正在尝试自动执行一些日常任务。我想要自动化的一项任务要求我“搜索”指定的标题,并选择整个数据列。然后,我会将该范围粘贴到不同的电子表格中。

Tamcolumn = Cells.Find(what:="plan_tamaward", after:="a1", searchdirection:=xlPrevious, searchorder:=xlBycolumn, lookat:=xlPart).Column

当我定义整个列时,我发现这一点代码有用,问题是我无法定义列标题并定义下面的范围而不“选择”数据 - 我知道是一个很大的禁忌。

我希望这是有道理的。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以将以下方法合并到您的代码中......

Dim Col As Long, LastRow As Long
Dim Rng As Range
If Application.CountIf(Rows(1), "plan_tamaward*") > 0 Then
    Col = Application.Match("plan_tamaward*", Rows(1), 0)
    LastRow = Cells(Rows.Count, Col).End(xlUp).Row
    Set Rng = Range(Cells(2, Col), Cells(LastRow, Col))
End If
If Not Rng Is Nothing Then
    MsgBox Rng.Address
    'do whatever you want to do with this range here
Else
    MsgBox "The column named like plan_tamaward* was not found in Row1.", vbExclamation, "Column Not Found!"
    Exit Sub
End If