我试图建立一个循环,该循环搜索标头并找到一个包含的值,在这种情况下为“ 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
答案 0 :(得分:1)
我不清楚您想要什么-但是从标题看来,您想根据标题文本获取列号?如果是这样,它将这样做:
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
答案 1 :(得分:0)
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.
'*******************************************************************************