简体   繁体   English

通过标题VBA定义范围

[英]Define Range by Header VBA

I have a range definition in VBA that looks like this: 我在VBA中有一个范围定义,如下所示:

Sheet5.Range(Range("K2"), Sheet5.Range("K2").End(xlDown))

This works but if the layout of my report ever changes, it will not work. 这有效,但如果我的报告的布局发生变化,它将无法正常工作。 I was wondering if it was possible to define the range based on the header in the first row of the column? 我想知道是否可以根据列第一行中的标题来定义范围? Any help with this issue would be greatly appreciated! 任何有关此问题的帮助将不胜感激!

The below example searches for the header based on the name. 以下示例根据名称搜索标头。 In the example, it colors the entire column Red based on match, but you can change that. 在该示例中,它根据匹配为整个列Red ,但您可以更改它。 The variables should be easy to follow, but please let me know of questions. 变量应该很容易理解,但请告诉我相关问题。

Sub Color_Range_Based_On_Header()
    Dim rngHeaders As Range
    Dim rngHdrFound As Range

    Const ROW_HEADERS As Integer = 1
    Const HEADER_NAME As String = "Location"

    Set rngHeaders = Intersect(Worksheets("Sheet1").UsedRange, Worksheets("Sheet1").Rows(ROW_HEADERS))
    Set rngHdrFound = rngHeaders.Find(HEADER_NAME)

    If rngHdrFound Is Nothing Then
        'Do whatever you want if the header is missing
        Exit Sub
    End If

    Range(rngHdrFound, rngHdrFound.End(xlDown)).Interior.Color = vbRed

End Sub

You can name a range with any kind of name you would like. 您可以使用任何您想要的名称命名范围。 In the upper left hand corner you can see the id of the selected range. 在左上角,您可以看到所选范围的ID。 If you type a name in there like "Header_Cell" you can change your code to: 如果您在其中键入名称“Header_Cell”,则可以将代码更改为:

Sheet5.Range(Range("Header_Cell"), Sheet5.Range("Header_Cell").End(xlDown))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM