【发布时间】:2015-07-14 23:07:48
【问题描述】:
我的代码在 VBA 中,并根据两个条件更新单元格的值。我已经对我的代码进行了相当广泛的评论,因此我将首先将其粘贴在下面。我通过添加两个撇号来更改 cmets,以便更容易区分 cmets 和此平台上的代码。
Sub HighlightValues()
'''Shortcut key: ctrl + w
'''Highlights values of corresponding left-most cell, if two conditions are met:
'''The part is in "L" class and all of the rightmost cells are empty
Dim ws As Worksheet
Dim i As Long, lastrow As Long, lastcolumn As Long, c As Long, d As Long, j As Long, count As Long, k As Long, report As Long
Set ws = Sheets("QAP")
lastrow = ws.Cells(Rows.count, 1).End(xlUp).Row
lastcolumn = ws.Cells(1, ws.Columns.count).End(xlToLeft).Column
'''Searches column titles for "Analysis Task Count"
'''where it will start searching for filled boxes on each row
For i = 1 To lastrow
If InStr(ws.Cells(1, i), "Analysis Task Count") Then
'''c is the number of column that Analysis Task Count is in
c = i - 1
End If
Next
'''Searches column titles for "Required by RPC"
'''where it will search for whether the part is "L' or not
For d = 1 To lastcolumn
If InStr(ws.Cells(1, d), "Required by RPC") Then
'''k is the number of column that Required by RPC is in
k = d
End If
Next d
'''For each row that part data is in
For i = 11 To lastrow
count = 0
'''If any cells past Analysis Task Count are filled, remember that
For j = c To lastcolumn
If Not IsEmpty(ws.Cells(i, j)) Then
count = 1
End If
Next j
'''If the stage is L and all the cells are empty for that row
If Cells(i, k).Value = ("L") And count = 0 Then
'''Highlight the first box in green
Cells(i, 1).Interior.Color = RGB(102, 255, 102)
Else
'''Or if thats not true, then make that box clear
Cells(i, 1).Interior.Color = xlNone
report = report + 1
End If
Next i
MsgBox (report)
End Sub
为了引导您浏览代码,(除了间距,某些格式没有保留),代码首先搜索两个关键列的列号,然后在最后一个 for 循环中,对于每一行,它搜索是否满足两个标准。如果满足条件,则单元格变为绿色,否则,将其填充为空白。我花了大约一个小时确认 k 和 c 返回的值都是正确的列号:我认为这不是问题。此外,当我设置计数以查看代码通过最后一个 for 循环和每个 if 语句的次数时,我得到了正确的循环数。
这很令人沮丧,唯一奇怪的是代码几乎是立即执行的,所以根本没有延迟。当然,单元格填充不会改变。为了测试这一点,我运行了用橙色填充单元格的代码,并且没有更改任何单元格。
感谢您为我提供的任何帮助!
【问题讨论】:
-
不知道什么是传入?我使用 Dim 来初始化它们,然后我找出它们的值,然后我使用最后一个循环中的值
-
为什么要将 c 设置为当前列 - 1 c = i - 1 。然后它正在查看从 c 开始的列。在不知道您的数据的情况下,我的测试在 c 中没有任何内容,因此它总是得到一个 count = 1 并且永远不会进入 if 语句来为单元格着色
-
仅供参考,你可以像这样得到最后一行和最后一列。 For i = 1 To ws.UsedRange.Rows.count 或 For i = 1 To ws.UsedRange.Columns.count