Sub sumexeptblack()
For Each cell In Range("4:4")
If cell.Font.Color <> 0 Then
Range("A3").Value = Range("A3").Value + cell.Value
End If
Next cell
End Sub
我编写这段代码并且它可以正常工作,但是当我把它放在另一个循环上时,excel只计算没有任何错误或结果。第二个代码是:
Sub sumallrowcolored()
Dim i As Integer
Dim e As Integer
e = 1
For i = 2 To 168 Step 2
e = i - e
For Each cell In Range("i:i")
If cell.Font.Color <> 0 Then
Range("Ae").Value = Range("Ae").Value + cell.Value
End If
Next cell
Next i
End Sub
答案 0 :(得分:2)
如果我正确理解了你的代码,你就试图迭代一行中的所有单元格(第一部分是行4
,第二部分是i
)。如果是这种情况,您将不得不像这样调整代码:
Sub sumallrowcolored()
Dim i As Integer
Dim e As Integer
e = 1
For i = 2 To 168 Step 2
e = i - e
For Each cell In Range(i & ":" & i)
If cell.Font.Color <> 0 Then
Range("A" & e).Value = Range("A" & e).Value + cell.Value
End If
Next cell
Next i
End Sub
答案 1 :(得分:1)
您需要检查何时使用引号以及何时在定义Range object时不使用引号。
Dim cell as range
Dim i As Long, e As Long
e = 1
For i = 2 To 168 Step 2
e = i - e
'For Each cell In Rows(i) 'could also be Range(i & ":" & i)
'better to cut it down to the .UsedRange
For Each cell In Intersect(ActiveSheet.UsedRange, Rows(i))
If cell.Font.Color <> 0 Then
'the following is a match operation; string concatenation should be a &, not a +
Range("A" & e) = Range("A" & e).Value + cell.Value
End If
Next cell
Next i
字符串连接运算符在VBA中是&amp; ,而不是 + 。 + 用于数学加法。我不完全确定你真正想要的是什么。
答案 2 :(得分:0)
对于您的第二部分代码,您需要将e
变量保留在语音标记之外,因为它仅在VBA中声明。尝试:
Sub sumallrowcolored()
Dim i As Integer
Dim e As Integer
e = 1
For i = 2 To 168 Step 2
e = i - e
For Each cell In Range("i:i")
If cell.Font.Color <> 0 Then
Range("A" & e).Value = Range("A" & e).Value + cell.Value
End If
Next cell
Next i
End Sub