代码之家  ›  专栏  ›  技术社区  ›  Andreas

基于列标题查找列

  •  0
  • Andreas  · 技术社区  · 7 年前

    我有这个代码,它只在我要找的标题在B列或“更高”时有效。
    假设我有这个表,需要找到“Name”和“score”列。

    Name    score
    John       1
    Joe        5
    

    如果B1中的“名称”和C1中的“分数”,则以下代码将起作用:

    NameColumn = Split(Cells(1, Cells(1, 1).EntireRow.Find(What:="Name", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, searchdirection:=xlNext, MatchCase:=True).Column).Address(True, False), "$")(0)
    ScoreColumn = Split(Cells(1, Cells(1, 1).EntireRow.Find(What:="score", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, searchdirection:=xlNext, MatchCase:=True).Column).Address(True, False), "$")(0)
                                                                    ^^ <- search value
    

    在这种情况下,上述代码将返回

    NameColumn = "B"
    ScoreColumn = "C"
    

    但假设这些列是A&B然后它将找不到“Name”,因为它开始在单元格1,1(A1)后搜索,而单元格1,1(A1)正是报头所在的位置。

    我可以做些什么来实现这一点,或者在上面的例子中,除了返回“A”和“B”,还有什么其他选择?

    2 回复  |  直到 7 年前
        1
  •  1
  •   IrwinAllen13    7 年前

    下面是我过去使用过的一个快速自定义函数。

    这可能不是最好的方法,但这是我多年来一直使用的方法。

    Function ColumnHeaderLocation(entry As String, Optional ColumnNumber As Boolean)
    Dim x, y As Long
    
    y = ActiveSheet.Columns.Count
    x = 1
    
    Do Until x > y
        If ActiveSheet.Cells(1, x).Value = entry Then
            ColumnHeaderLocation = Split(ActiveSheet.Cells(1, x).Address(True, False), "$")(0)
            If ColumnNumber = True Then ColumnHeaderLocation = x
            Exit Function
        Else
            x = x + 1
        End If
    Loop
    
    End Function
    

    只需使用列标题的名称(参见示例)。。。

    NameColumn = ColumnHeaderLocation("Name") ' returns Column Location as a letter

    或

    NameColumn = ColumnHeaderLocation("Name", True) ' Returns column Location as a Number

        2
  •  0
  •   VBasic2008    7 年前

    标题栏字母计算

    您必须添加 After 对 Find 方法指向最后一个单元格 .Cells(.Cells.Count) 从第一个单元格开始搜索 .Cells(1) .但作为 chris neilsen 在评论中指出,这不是你的代码失败的原因,因为它会发现 Name 在搜索结束时。
    因为你还没有定义“不工作”的真正含义,而且你不太可能拼写错误 名称 在里面 A1 ,我想 NameColumn 返回不需要的结果( <>A )意思是你用过 名称 在第一行的其他地方,你真的需要从第一个单元格开始搜索 .细胞(1) .

    短版

    Sub FindAfterShort()
    
        Dim NameColumn As String   ' Name Column Letter
        Dim ScoreColumn As String  ' Score Column Letter
    
        With Rows(1)
            NameColumn = Split(.Find("Name", .Cells(.Cells.Count), xlValues, _
                    xlWhole).Address, "$")(1)
            ScoreColumn = Split(.Find("Score", .Cells(.Cells.Count), xlValues, _
                    xlWhole).Address, "$")(1)
        End With
    
        Debug.Print "Column Letters '" & NameColumn & "' and '" & ScoreColumn & "'."
    
    End Sub
    

    更好的版本

    Sub FindAfterPref()
    
        Const cSheet As String = "Sheet1"   ' Worksheet Name
    
        Dim strName As String   ' Name Column Letter
        Dim strScore As String  ' Score Column Letter
    
        With ThisWorkbook.Worksheets(cSheet).Rows(1)
            strName = Split(.Find("Name", .Cells(.Cells.Count), xlValues, _
                    xlWhole).Address, "$")(1)
            strScore = Split(.Find("Score", .Cells(.Cells.Count), xlValues, _
                    xlWhole).Address, "$")(1)
        End With
    
        Debug.Print "Column Letters '" & strName & "' and '" & strScore & "'."
    
    End Sub
    

    小书房

    Sub FindAfter()
    
        Const cSheet As String = "Sheet1"   ' Worksheet Name
        Const cFR As Long = 2               ' First Row
        ' The column where the Last Row Number will be calculated.
        Const cLRColumn As Variant = "A"    ' Last-Row Column Letter/Number
    
        Dim rngName As Range    ' Name Column Range, Name Range
        Dim rngScore As Range   ' Score Column Range, Score Range
        Dim lngName As Long     ' Name Column Number
        Dim lngScore As Long    ' Score Column Number
        Dim strName As String   ' Name Column Letter
        Dim strScore As String  ' Score Column Letter
        Dim lngLR As Long       ' Last Row Number (Calculated in Last-Row Column)
    
        With ThisWorkbook.Worksheets(cSheet).Rows(1)
    
            ' Find Method Arguments
            '   2. After: If you want to start the search from the first cell, you
            '             have to set the After parameter to the last cell. If you
            '             have the matching data in the first cell and you set the
            '             parameter to the first cell (default), it will still be
            '             found, but a little later (not mili, but micro seconds
            '             later) so it could be omitted.
            '   5. SearchOrder: Whenever a range is a one-row or a one-column range,
            '                   this argument can be omitted. Since you're searching
            '                   in a one-row range, "xlByRows" would have been the
            '                   more 'correct' way in this case.
            '   6. SearchDirection: This argument's parameter is by default "xlNext"
            '                       and can therefore be omitted
            '   7. MatchCase: This argument's parameter is by default "False". Since
            '                 I don't see the reason why you would have headers with
            '                 the same name, especially the ones you don't need
            '                 before the ones you need, it is omitted. If you really
            '                 need it, use "... xlWhole, , , True".
            Set rngName = .Find("Name", .Cells(.Cells.Count), xlValues, xlWhole)
            Set rngScore = .Find("Score", .Cells(.Cells.Count), xlValues, xlWhole)
    
            ' Address Arguments
            ' If the Address arguments are omitted, Range.Address returns the
            ' address as an absolute reference e.g. $A$1. When you split
            ' $A$1 you will get the following
            ' INDEX STRING
            '   0           - Empty string ("").
            '   1      A    - Use this i.e. index 1 for the split array index.
            '   2      1
            If Not rngName Is Nothing Then ' When "Name" was found.
                ' Calculate Name Column Number.
                lngName = rngName.Column
                ' Calculate Name Column Letter.
                strName = Split(rngName.Address, "$")(1)
            End If
            If Not rngScore Is Nothing Then ' When "Score" was found.
                ' Calculate Score Column Number.
                lngScore = rngScore.Column
                ' Calculate Score Column Letter.
                strScore = Split(rngScore.Address, "$")(1)
            End If
    
            Debug.Print "Column Numbers '" & lngName & "' and '" & lngScore & "'."
            Debug.Print "Column Letters '" & strName & "' and '" & strScore & "'."
            Debug.Print "Name Column Header Address '" & rngName.Address & "'."
            Debug.Print "Score Column Header Address '" & rngScore.Address & "'."
    
            With .Parent ' instead of "ThisWorkbook.Worksheets(cSheet)".
    
                '*******************************************************************
                ' This should demonstrate a case where you don't need the column
                ' letter (mostly you don't). You should use ".Cells", ".Range" is
                ' not an option.
                '*******************************************************************
                ' Column Number (lngName)
                ' Last Row Number calculated using Cells and lngName.
                If lngName <> 0 Then
                    ' Calculate last row in Name Column.
                    lngLR = .Cells(.Rows.Count, lngName).End(xlUp).Row
                    ' Create a reference to the range from First Row to Last Row in
                    ' Name Column.
                    Set rngName = .Range(.Cells(cFR, lngName), _
                            .Cells(lngLR, lngName))
                End If
    
                '*******************************************************************
                ' This is the same as the previous and should demonstrate that
                ' when you already know the column letter, you have two choices:
                ' you can use ".Cells" or ".Range".
                '*******************************************************************
                ' Column Letter (strName)
                ' Last Row Number calculated using Cells and strName.
                If strName <> "" Then
                    ' Calculate last row in Name Column.
                    lngLR = .Cells(.Rows.Count, strName).End(xlUp).Row
                    ' Create a reference to the range First Row to Last Row in
                    ' Name Column.
                    Set rngName = .Range(.Cells(cFR, strName), _
                            .Cells(lngLR, strName))
                End If
                ' Last Row Number calculated using Range and strName.
                If strName <> "" Then
                    ' Calculate last row in Name Column.
                    lngLR = .Range(strName & .Rows.Count).End(xlUp).Row
                    ' Create a reference to the range from First Row to Last Row in
                    ' Name Column.
                    Set rngName = .Range(strName & cFR & ":" & strName & lngLR)
                End If
                '*******************************************************************
    
                ' Since the column letter is more user-friendly, the only use
                ' I can imagine where you might need it, is to inform the user e.g.
                MsgBox "Column '" & strName & "' contains the names and column '" _
                        & strScore & "' contains the scores.", vbInformation, _
                        "User Information"
    
            End With
    
            Debug.Print "Last (used) Row in Name Column '" & lngLR & "'."
            Debug.Print "Name Range Address '" & rngName.Address & "'."
            Debug.Print "Column '" & strName & "' contains the Names and column'" _
                    & strScore & "' contains the scores."
    
        End With
    
    End Sub