excel - 在列中查找下一个红色单元格,返回该单元格的行号
问题描述
我正在寻找一个函数/宏,它可以在我的工作表的 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:需要列中下一个红色单元格的行号,而当单元格为空时循环该列以跳转到下一个红色表头
解决方案
您可以使用内置的 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。
推荐阅读
- shell - zsh:解析zsh命令参数中使用的变量中的通配符?
- android - 如何使用具有不同构建类型 (Android/Studio) 的 GitHub 版本控制?
- sql - 如何获取涉及三个SQL表的最旧数据
- python - Seaborn/Matplotlib 沿线创建自定义错误带
- node.js - 在 express 开始之前用 await 加载
- javascript - React Native 中的 WebView 整页截图
- angular - Angular 客户端应用程序可以接收带有正文的 http GET 请求吗?
- pyspark - 变量等于pyspark上的doublemetaphone
- python - Pandas read_csv:使用单个变量加载多个文件 - 日期转换函数出现未绑定错误
- javascript - 为什么每个生产部署都需要清除浏览器缓存