首页 > 解决方案 > 在列中查找下一个红色单元格,返回该单元格的行号

问题描述

我正在寻找一个函数/宏,它可以在我的工作表的 A 列中找到下一个红色单元格。基本上我想做的是循环通过A列,每次我找到一个空单元格时,跳到下一个红色单元格并在那里继续循环。我所需要的只是下一个红色单元格的行号,以便执行此操作。到目前为止我的工作是这样的:

'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

整个表看起来像这样:在此处输入图像描述 不同的红色表部分之间的空行数量可能会有所不同,这就是为什么当它找到一个空行(我目前的方法)时只下降一定数量的行不起作用。

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

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

TLDR:需要列中下一个红色单元格的行号,而当单元格为空时循环该列以跳转到下一个红色表头

标签: excelvbaloopsfindoffice365

解决方案


您可以使用内置的 ExcelFind功能来搜索格式。以下函数将返回具有特定背景颜色的下一个单元格,或者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

(如果它更适合您的需要,请将返回值更改为Long并返回cell.Row

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


推荐阅读