Поиск столбца на основе заголовка, а затем форматирование строк - PullRequest
0 голосов
/ 06 декабря 2018

Я пытаюсь построить цикл, который просматривает заголовки и находит содержащееся в нем значение, в данном случае «Avg».Если значение найдено, оно будет работать вниз по столбцу и будет применять формат, основанный на сравнении с другим столбцом.Я пытаюсь преобразовать мою переменную ячейки в цикле For (Z) в адрес столбца, чтобы я мог использовать ее для управления значением ws.Cells () в следующем цикле.

Любая помощь очень ценится, спасибо !!!!

Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
Dim Z As Range
lastRow = ws.Cells(ws.Rows.Count, "I").End(xlUp).Row

For Each Z In Range("I1:BM1").Cells
    If InStr(1, Z.Value, "Avg") Then

        For i = 2 To lastRow 'loop from row 2 to last
            If ws.Cells(i, 8) - ws.Cells(i, Z) < 0 Then 
                ws.Cells(i, Z).Interior.ColorIndex = 4 
            End If
        Next i
    End If
Next Z
End Sub

Ответы [ 2 ]

0 голосов
/ 06 декабря 2018

Поиск заголовка и форматирование ячеек

Option Explicit

'*******************************************************************************
' Purpose:    Finds a column containing a specified header and applies
'             formatting to its cells that match a criteria.
'*******************************************************************************
Sub FindHeaderFormatCells()

    Const vntLast As Variant = "I"        ' Last Row Column e.g. "I" or 9
    Const strRange As String = "I1:BM1"   ' Search Range
    Const strHeader As String = "Avg"     ' Search Column Header Title
    Const vntMatch As Variant = 8         ' Match Column e.g. 8 or "H"
    Const intColor As Integer = 4         ' ColorIndex for Match (Bright Green)

    Dim rngCell As Range                  ' Range Control Variable

    Dim lastRow As Long                   ' Last Row of Data in column vntLast
    Dim i As Long                         ' Rows Counter
    Dim j As Integer                      ' Search Column

    With ThisWorkbook.Worksheets("Sheet1")

        lastRow = .Cells(Rows.Count, vntLast).End(xlUp).Row

        ' Calculate Search Column (j) by finding the column containing
        ' Search Column Header Title (strHeader) in Search Range (strRange).
        For Each rngCell In .Range(strRange).Cells
            ' vbTextCompare i.e. no matter if "Avg" or "AVG" or "avg" or...
            If InStr(1, rngCell.Value, strHeader, vbTextCompare) Then
              j = rngCell.Column
              Exit For ' When found, no need to search anymore.
            End If
        Next

        ' When Search Column Header Title is NOT found.
        If j = 0 Then GoTo SearchErr

        ' Apply colors to Search Column cells that match criteria.
        For i = 2 To lastRow
            If .Cells(i, vntMatch) - .Cells(i, j) < 0 Then
                .Cells(i, j).Interior.ColorIndex = intColor
            End If
        Next

    End With

Exit Sub  ' Program ends here if Search Column Header Title was found.

SearchErr:
    MsgBox "Could not find the header title (" & strHeader & ") in the " _
      & "specified range (" & strRange & ")."

End Sub   ' Program ends here if Search Column Header Title was NOT found.
'*******************************************************************************
0 голосов
/ 06 декабря 2018

Мне не совсем понятно, что вы хотите - но из заголовка видно, что вы хотите получить номер столбца на основе текста заголовка?Если так, то это будет сделано:

 Private Function GetColumn(headerName As String) As Integer

    Dim col As Integer
    GetColumn = 0
    For col = 1 To ActiveSheet.UsedRange.Columns.Count
        If ActiveSheet.Cells(1, col).Value = headerName Then
            GetColumn = col
            Exit For
        End If
    Next col

End Function
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...