在vba中设置自定义和颜色公式

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 

如果我正确理解你的代码,你试图遍历一行中的所有单元格(在第一部分行是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 

在定义Range对象时,您需要检查何时使用引号以及何时不使用引号。

 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 

string连接运算符是一个 in VBA,而不是++是math加法。 我不完全确定你究竟想要什么。

对于代码的第二部分,您需要将evariables保留在语音标记之外,因为它只在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