[英]If elseif statement Excel VBA
In column AI have target production, in column BI have actual production, and in column CI have the delta between the two. 在AI列中有目标产量,在BI列中有实际产量,在CI列中有两者之间的差异。 I simply want to loop through each row in column C and flag each value according to a strategic bucket. 我只想遍历C列中的每一行,并根据策略存储区标记每个值。 The sample code I tried before going into master document is below. 下面是我进入主文档之前尝试的示例代码。
My issue is surrounding how to perform the action on the current cell in the loop. 我的问题是如何在循环中的当前单元格上执行操作。 The code is just coloring the last cell I clicked on instead of the cell being evaluated. 代码只是为我单击的最后一个单元格着色,而不是对要评估的单元格进行着色。 Any suggestions? 有什么建议么?
Sub StratBuckets()
Dim Delta As Variant
Dim n As Integer
n = 0
For n = 0 To 15
' works up to this point --> points to the right value
Delta = Worksheets("Test").Range("A1:Z1000").Find("Start Date").Offset(n, 3).Value
If Delta > 0 And Delta <= 10 Then
ActiveCell.Interior.Color = vbYellow
ElseIf Delta > 10 Then
ActiveCell.Interior.Color = vbGreen
ElseIf Delta < 0 Then
ActiveCell.Interior.Color = vbRed
Else
End If
Next n
End Sub
You need to apply .Interior.Color
on the right cell. 您需要在正确的单元格上应用.Interior.Color
。
If Worksheets("Test").Range("A1:Z1000").Find("Start Date").Offset(n, 3)
is the cell you want to colorize, then do : 如果Worksheets("Test").Range("A1:Z1000").Find("Start Date").Offset(n, 3)
是要着色的单元格,则请执行以下操作:
Worksheets("Test").Range("A1:Z1000").Find("Start Date").Offset(n, 3).Interior.Color = ...
Another way to go, is to Set a Range DeltaRng
to the Find
with: 另一种方法是,使用以下方法将范围DeltaRng
设置为“ Find
:
Worksheets("Test").Range("A1:Z1000").Find("Start Date")
, Worksheets("Test").Range("A1:Z1000").Find("Start Date")
,
then if the Find
is successful, get the Delta
value 3 column on the right with Delta = DeltaRng.Offset(n, 3).Value
. 然后,如果Find
成功,则使用Delta = DeltaRng.Offset(n, 3).Value
获取右侧的Delta
值3列。
At last, when you are inside your If Delta > 0 And Delta <= 10 Then
etc.. you can modify the .Interior.Color
of the cell with DeltaRng.Offset(n, 3).Interior.Color = vbYellow
. 最后,当你在你的内If Delta > 0 And Delta <= 10 Then
等..你可以修改.Interior.Color
与细胞的DeltaRng.Offset(n, 3).Interior.Color = vbYellow
。
Code 码
Sub StratBuckets()
Dim DeltaRng As Range
Dim Delta As Variant
Dim n As Long
For n = 0 To 15
' works up to this point --> points to the right value
Set DeltaRng = Worksheets("Test").Range("A1:Z1000").Find("Start Date") '.Offset(n, 3).Value
If Not DeltaRng Is Nothing Then '<--make sure Find was successful
Delta = DeltaRng.Offset(n, 3).Value '<-- find the Delta value 3 columns to the right
If Delta > 0 And Delta <= 10 Then
DeltaRng.Offset(n, 3).Interior.Color = vbYellow
ElseIf Delta > 10 Then
DeltaRng.Offset(n, 3).Interior.Color = vbGreen
ElseIf Delta < 0 Then
DeltaRng.Offset(n, 3).Interior.Color = vbRed
End If
End If
Next n
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.