查找列中的下一个红色单元格,Return 该单元格的行号

Find Next Red Cell in Column, Return Rownumber of that Cell

我正在寻找一个 function/macro,它可以在我的工作表的 A 列中找到下一个红色单元格。基本上我想做的是循环遍历 A 列,每次我找到一个空单元格时,跳到下一个红色单元格并在那里继续循环。我只需要下一个红色单元格的行号即可进行 thuis。到目前为止我的工作是这样的:

'Loop through column A from top down starting in row 6 and create Chart for each row
For rownumber = 6 To LastRow Step 1

'If Cell is filled
If TPsheet.Cells(rownumber, 1) <> "" Then
'Create Chart
Call CreateChart()
Else
rownumber = rownumber + 2 (This is the problem area, just going down 2 rows sadly doesnt work as sometimes there are 3/4/5 consecutive empty rows, need to set this to rownumber of next red cell)
End If

Next rownumber

整个table看起来像这样: 并且不同红色 tables 部分之间的空行数量可能会有所不同,这就是为什么当它发现一个空行(我当前的方法)时只向下移动一定数量的行是行不通的。

为了找到一个红细胞,我在另一个宏中成功地使用了这个:

Do Until i = 1000
    If TPsheet.Range("A" & i).Interior.Color = RGB(255, 0, 0) Then
       '...  
    End If
i = i + 1
Loop

TLDR:需要列中下一个红色单元格的行号,同时在单元格为空时循环遍历该列以跳转到下一个红色 table header

如果您已经越过最后一条红线,这将花费很多时间。

Function GetNextRedInteriorRowNumber() As Long

Dim i As Long
Dim c As Long
Dim retVal As Long

retVal = -1
c = ActiveCell.Column

For i = ActiveCell.Row + 1 To ActiveSheet.Rows.Count
    
    If ActiveSheet.Cells(i, c).Interior.Color = RGB(255, 0, 0) Then
        retVal = i
        Exit For
    End If
Next

GetNextRedInteriorRowNumber = retVal

End Function

您可以使用内置的 Excel Find 功能来搜索格式。以下函数将 return 下一个具有特定背景颜色的单元格,或者 Nothing 如果在特定点下方找不到单元格。

Function FindColoredCell(ws As Worksheet, searchColor As Long, Optional afterCell As Range = Nothing) As Range
    If afterCell Is Nothing Then Set afterCell = ws.Cells(1, 1)
    ' Set the search parameter for the specific color.
    With Application.FindFormat.Interior
        .Pattern = xlSolid
        .color = searchColor
    End With
    ' Do the search
    Dim cell As Range
    Set cell = ws.Cells.Find(What:="", after:=afterCell, SearchDirection:=xlNext, SearchFormat:=True)
    If cell Is Nothing Then Exit Function           ' now cell found with color
    If cell.row < afterCell.row Then Exit Function  ' now cell below "afterCell", Search started at top
    Set FindColoredCell = cell
End Function

(如果它更符合您的需要,将 return 值更改为 Long 和 return cell.Row

注意:在您的代码中,您正在使用 For-循环。如果您要在循环中修改计数变量(在您的例子中为 rowNumber),请不要这样做,否则您将得到不可预测的结果。请改用 do Do While-Loop。