如果是elseif语句Excel VBA

时间:2017-02-07 22:46:30

标签: excel excel-vba vba

在A栏中我有目标生产,在B栏中我有实际生产,在C栏中我有两者之间的差异。我只想循环遍历C列中的每一行,并根据策略桶标记每个值。我在进入主文档之前尝试的示例代码如下所示。

我的问题是如何在循环中对当前单元格执行操作。代码只是着色我点击的最后一个单元格而不是被评估的单元格。有什么建议?

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

2 个答案:

答案 0 :(得分:3)

您需要在正确的单元格上应用.Interior.Color

如果Worksheets("Test").Range("A1:Z1000").Find("Start Date").Offset(n, 3)是要着色的单元格,请执行以下操作:

Worksheets("Test").Range("A1:Z1000").Find("Start Date").Offset(n, 3).Interior.Color = ...

答案 1 :(得分:1)

另一种方法是将范围DeltaRng设置为Find,其中包含:

Worksheets("Test").Range("A1:Z1000").Find("Start Date")

然后,如果Find成功,请使用Delta获取右侧的Delta = DeltaRng.Offset(n, 3).Value值3列。

最后,当您进入If Delta > 0 And Delta <= 10 Then等...时,您可以使用.Interior.Color修改单元格的DeltaRng.Offset(n, 3).Interior.Color = vbYellow

<强>代码

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