vba - 如果满足条件,Excel VBA冻结双循环为特定范围着色
问题描述
你好!
我还是 VBA 的新手,但是使用几乎我所有的脑细胞,我设法构建了下面的代码。
但是,当我执行宏时,Excel 似乎工作了很长时间,但什么也没做。我没有收到任何错误消息,但似乎 Excel 陷入了无限循环。
我怀疑我的代码某处存在重大缺陷,但我似乎无法弄清楚在哪里。
Sub Makro_color_cells()
Application.ScreenUpdating = False
Dim groupfrom As Range
Dim groupto As Range
Dim groupfinal As Range
lastrow = Cells(Rows.Count, "B").End(xlUp).Row
x = 4
t = 0
Do While x < lastrow
Set groupfrom = Cells(x - 1, "F")
Cells(x - 1, "B").Activate
Do While ActiveCell = ActiveCell.Offset(1, 0)
t = t + 1
ActiveCell.Offset(1, 0).Activate
Loop
x = x + t
Set groupto = Cells(x - 1, "F")
Set groupfinal = Range(groupfrom, groupto)
If Not (groupfinal.Find("Storage") Is Nothing) Then
Range("groupfinal").Interior.ColorIndex = 3
End If
t = 0
Set groupfrom = Nothing
Set groupto = Nothing
Set groupfinal = Nothing
Loop
Application.ScreenUpdating = True
End Sub
代码的目的是根据某些标准为 F 列中的某些单元格着色:
B 列包含数字,其中重复项彼此相邻。将 B 列中具有相同值的所有行视为一个“组”。
现在,如果“组”中的一行或多行在 F 列中包含文本“Storage”,则该“组”中的所有行都应将其 F 列着色。
我的代码背后的基本思想是定位“组”并使用groupfrom
并groupto
设置一个groupfinal
等于F列中组单元格的范围。
然后使用该range.find
方法测试是否出现“存储”。
我尝试了故障排除,但没有运气。
任何想法为什么代码不起作用?
我感谢任何帮助,并且我对采用与我的代码不同的方法的想法持开放态度。
先感谢您!
解决方案
由于您的所有组将组合在一起而不是混合在一起,因此可以使用 vba 脚本来检查组值,使用该值的总数来定义范围并更改 F 列中的单元格颜色:
Sub Makro_color_cells()
Dim LastRow
Dim CurrentRow
Dim GroupValue
Dim GroupTotal
Dim GroupCheck
GroupValue = Range("B1").Value ' get the first value to search
CurrentRow = 1 ' Define the starting row
With ActiveSheet ' find the last used cell in the column
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
For x = 1 To LastRow ' start the reapat until last cell reached
GroupTotal = Application.WorksheetFunction.CountIf(Range("B1:B" & LastRow), GroupValue) ' search for total of the group values
GroupCheck = Application.WorksheetFunction.CountIf(Range("F" & CurrentRow & ":F" & CurrentRow + GroupTotal - 1), "Storage") ' search for "Storage" in the range from current row to total rows of the same group values
If GroupCheck >= 1 Then ' if the "Storage" search is equal to one or more then colour the range of cells
Range("F" & CurrentRow & ":F" & CurrentRow & ":F" & CurrentRow + GroupTotal - 1).Interior.ColorIndex = 3
End If
CurrentRow = CurrentRow + GroupTotal ' We know how many cells are in the same group so we can bypass them and move the current row to the next group of values
GroupValue = Range("B" & CurrentRow).Value ' Get the value for the new group
If GroupValue = "" Then ' Check the new group value and if it is nothing then we can exit the 'For Next x'
Exit For
End If
Next x
End Sub
推荐阅读
- angularjs - 从 web api 控制器将 xml 传递给 angular
- python - 需要不和谐机器人的帮助
- python - 正则表达式匹配下一行中的单词
- python - Python Sum if:使用来自不同 pandas 列的数据
- python - 包装元素以在python中列出
- javascript - 如何将项目放在分页中并显示项目编号是否大于 4
- redis - 使用 Spring Data Redis 2.0.3 的缓存管理器
- javascript - HTML / Javascript - 尝试以页面指针为指导
- java - pdfbox 将 acroform 保存为普通 pdf
- javascript - 如何使用 JavaScript 使有效的 xml 文件看起来干净整洁