![](/img/trans.png)
[英]Displaying graphs when certain criteria is met in Excel using if statements or vba
[英]Excel VBA Freezing double loop to color certain range if criteria is met
你好!
我还是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列中具有文本“存储”,则该“组”中的所有行都应为其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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.