您好!
我还是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
方法测试是否出现“存储”。
我尝试过排查,但没有运气。
有什么想法为什么代码不起作用?
我感谢任何帮助,并且我对采用与我的代码不同的方法持开放态度 提前谢谢!
答案 0 :(得分:1)
由于所有组都将组合在一起而不是混合,因此可以使用vba脚本检查组值,使用该值的总数来定义范围并更改F列中的单元格颜色: / p>
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