excel - 使用 for 循环来识别行
问题描述
我试图根据第一列中单元格的字符串内容突出显示一行。
例如,如果第一列中的单元格包含字符串“Total”,则以较深的颜色突出显示该行。
Sub tryrow()
Dim Years
Dim rownum As String
Years = Array("2007", "2008", "2009") ' short example
For i = 0 To UBound(Years)
Set rownum = Range("A:A").Find(Years(i) & " Total", LookIn:=xlValues).Address
Range(rownum, Range(rownum).End(xlToRight)).Interior.ColorIndex = 1
Next i
End Sub
我收到此错误消息:
编译错误:需要对象
编辑器突出显示rownum =
,就好像这个对象没有用 初始化一样Dim rownum As String
。
解决方案
您在这里遇到了几个问题,如下所示:
Sub tryrow()
Dim Years() As String 'Best practice is to dim all variables with types. This makes catching errors early much easier
Dim rownum As Range 'Find function returns a range, not a string
Years = Array("2007", "2008", "2009") ' short example
For i = 0 To UBound(Years)
Set rownum = Range("A:A").Find(Years(i) & " Total", LookIn:=xlValues) 'Return the actual range, not just the address of the range (which is a string)
If Not rownum Is Nothing Then 'Make sure an actual value was found
rownum.EntireRow.Interior.ColorIndex = 15 'Instead of trying to build row range, just use the built-in EntireRow function. Also, ColorIndex for gray is 15 (1 is black, which makes it unreadable)
End If
Next i
End Sub
推荐阅读
- javascript - 带有动态小数的 HTML 输入数字的 jQuery 数字格式
- dataframe - 在 Dash 中使用下拉框过滤数据表
- angular - 如何以角度动态更改从 json 文件中检索到的图像?
- angular - Angular 支持的版本格式
- azure - Azure 专用 SQL 池(以前的 SQL DW)将从 Azure 中删除?
- angular - 如何为 Angular 11 安装 ngx-bootstrap v7.0.0?
- node.js - 从 ES6 模块导入 commonjs 默认值
- next.js - Vercel 上的 Next.js API 超时
- vb.net - 将文本分隔到列
- c# - Puppeteer Sharp 提交表单