使用以下代码,我遍历大约200个单元格的范围[范围(" R"& i)]以检查Temp_Sheet.Range(" B2")值在范围内。以下代码效果很好。
问题在于:如果循环完成并且未找到该范围内的值,我需要将B2值添加到下一个空行。我该怎么做呢?在此先感谢您的帮助。如果没有找到值,我可以在循环中添加将触发另一个子/函数的格式吗?
For i = 6 To ColarLastRow
If ChangeSheet.Range("R" & i).Value = Temp_Sheet.Range("B2") Then
ChangeSheet.Range("G" & i) = Sum_Range
ChangeSheet.Range("G" & i).Interior.Color = RGB(0, 100, 0)
Else: End If
Next i
答案 0 :(得分:1)
你需要在循环中设置一些标志:
Dim AddNew As Boolean
AddNew = True
For i = 6 To ColarLastRow
If ChangeSheet.Range("R" & i).Value = Temp_Sheet.Range("B2") Then
ChangeSheet.Range("G" & i) = Sum_Range
ChangeSheet.Range("G" & i).Interior.Color = RGB(0, 100, 0)
AddNew = False
Else: End If
Next i
If AddNew Then
'place your code here
End If
答案 1 :(得分:0)
Dim counter as Integer
counter = 0
For i = 6 To ColarLastRow
If ChangeSheet.Range("R" & i).Value = Temp_Sheet.Range("B2") Then
ChangeSheet.Range("G" & i) = Sum_Range
ChangeSheet.Range("G" & i).Interior.Color = RGB(0, 100, 0)
Counter = counter + 1
Else: End If
Next i
If counter = 0 then
ChangeSheet.Range("R" & ChangeSheet.Range("R" & ChangeSheet.Rows.Count).End(xlUp).Offset(1,0) = Temp_Sheet.Range("B2")
End If
答案 2 :(得分:0)
dim Rng as Range
Set rng = ChangeSheet.Range("R6:R" & ColarLastRow).Find _
(What:=Temp_Sheet.Range("B2"), LookIn:=xlValues)
'set LookIn:=xlValues, xlFormulas, as appropriate
'set MatchCase:=True or False, as appropriate
If Rng is Nothing then
ChangeSheet.Range("R" & ColarLastRow+1).Value = 'something
'set color here
Else
ChangeSheet.Range("G" & rng.row) = Sum_Range
End if
使用.Find将比循环快得多。如果您需要查找多个匹配项,请在Set Rng =
之后添加:
Set rng = ChangeSheet.Range("R6:R" & ColarLastRow).Find _
(What:=Temp_Sheet.Range("B2"), LookIn:=xlValues)
While Not Rng is Nothing
'do your stuff here
Set rng = ChangeSheet.Range("R" & Rng.Row & ":R" & ColarLastRow).Find _
(What:=Temp_Sheet.Range("B2"), LookIn:=xlValues)
Wend
答案 3 :(得分:0)
看起来已经有了一些很好的答案,但这就是我想出的......
Dim ChangeSheet As Worksheet
Dim Temp_Sheet As Worksheet
Dim ValueFound As Boolean
Set ChangeSheet = Sheets("ChangeSheet")
Set Temp_Sheet = Sheets("Temp_Sheet")
ColarLastRow = ChangeSheet.Cells(Rows.Count, 18).End(xlUp).Row
ValueFound = False
For i = 6 To ColarLastRow
If ChangeSheet.Range("R" & i).Value = Temp_Sheet.Range("B2") Then
ChangeSheet.Range("G" & i) = Sum_Range
ChangeSheet.Range("G" & i).Interior.Color = RGB(0, 100, 0)
ValueFound = True
Else: End If
Next i
If ValueFound = False Then
ChangeSheet.Range("R" & ColarLastRow + 1).Value = Temp_Sheet.Range("B2").Value
End If