[英]Make cells negative based upon the value of another
I'm able to colour cells based upon the value of another with the code below, which I found on this forum我可以使用下面的代码根据另一个值为单元格着色,这是我在这个论坛上找到的
Sub ColorMeElmo()
Dim i As Long, r1 As Range, r2 As Range
For i = 2 To 100
Set r1 = Range("D" & i)
Set r2 = Range("A" & i & ":C" & i)
If r1.Value = "Aankoop" Then r2.Interior.Color = vbRed
If r1.Value = "Verkoop" Then r2.Interior.Color = vbBlue
If r1.Value = "Dividend" Then r2.Interior.Color = vbYellow
Next i
End Sub
Now I'm trying to make cells negative or possitive based upon the value of r1.现在我试图根据 r1 的值使单元格为负或正。 I tried this:
我试过这个:
If r1.Value = "Verkoop" Then r2.Value = r2.Value * (-1)
Ibrez's answer is right. Ibrez 的回答是正确的。 Anyway, I would recommend you write some clearer and more performant code (having 3 conditionals in each loop could be kind of slow if you have a big data sheet).
无论如何,我建议您编写一些更清晰、更高效的代码(如果您有一个大数据表,每个循环中有 3 个条件可能会有点慢)。 This is my suggestion:
这是我的建议:
Public Sub ColorMeElmo()
Dim i As Long, r1 As Range, r2 As Range, r3 As Range
Dim color As Long
Dim value2 As Integer, value3 As Integer
For i = 2 To 100
Set r1 = Range("A" & i)
Set r2 = Range("B" & i)
Set r3 = Range("C" & i)
Select Case r1
Case "Aankoop"
color = vbRed
value2 = r2
value3 = r3
Case "Verkoop"
color = vbBlue
value2 = -r2
value3 = -r3
Case "Dividend"
color = vbYellow
value2 = r2
value3 = r3
Case Else
'some unexpected value would be highlighted in grey
color = RGB(127, 127, 127)
value2 = r2
value3 = r3
End Select
r2.Interior.color = color
r2 = value2
r3.Interior.color = color
r3 = value3
Next i
End Sub
Issue seems to be that r2 contains multiple cells hence below code will not work问题似乎是 r2 包含多个单元格,因此下面的代码将不起作用
If r1.Value = "Verkoop" Then r2.Value = r2.Value * (-1)
This needs to be changed to这需要更改为
If r1.Value = "Verkoop" Then
For Each c In r2.Cells
c.Value = c.Value * (-1)
Next
End if
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.