2016-09-29 40 views
1
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只是计算没有任何错误或结果。第二码为:在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("Ae").Value = Range("Ae").Value + cell.Value 
      End If 
     Next cell 
    Next i 

End Sub 
+0

你在哪里使用过'Range(“i:i”)'你想为每个循环做些什么?因为'Range(“2:2”)'将会出错,就像任何没有提供列字母的地方一样。 – Jordan

+1

@Jordan - 'Range(“2:2”)'是'A2:XFD2'或整个第二行。证明在立即窗口与'?范围(“2:2”)。地址' – Jeeped

回答

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 
+0

非常感谢...它的工作 有一点变化,'e =我 - e'必须'e = i - 1' –

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 
+0

感谢您的答复哥们;) –

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,而不是一个++用于数学加法。我不完全确定你究竟想要什么。

+0

绝对正确... 感谢您的解释 –

相关问题