Excel VBA If ElseIf语句不返回正确的结果

Excel VBA If ElseIf语句不返回正确的结果,excel,vba,Excel,Vba,我的If-ElseIf语句有问题,因为单元格值没有返回正确的结果 以下是我的模块中的代码: 第一批: Sub compare2() Dim i As Long Dim A As Long Dim B As Long Dim c As Long A = 14 B = 15 c = 16 Do While A <= 42 i = 2 Do Until Len(Cells(i, A)) = 0 If Cells(i, A) = "Green" And Cells(i, B) = "Roll

我的If-ElseIf语句有问题,因为单元格值没有返回正确的结果

以下是我的模块中的代码:

第一批:

Sub compare2()
Dim i As Long
Dim A As Long
Dim B As Long
Dim c As Long

A = 14
B = 15
c = 16

Do While A <= 42
i = 2
Do Until Len(Cells(i, A)) = 0

If Cells(i, A) = "Green" And Cells(i, B) = "Rollup" Then
Cells(i, c) = "Green"

ElseIf Cells(i, A) = "Rollup" And Cells(i, B) = "Rollup" Then
Cells(i, c) = "Rollup"

ElseIf Cells(i, A) = "Rollup" And Cells(i, B) = "Green" Then
Cells(i, c) = "Green"

ElseIf Cells(i, A) = "Rollup" And Cells(i, B) = "Yellow" Then
Cells(i, c) = "Yellow"

ElseIf Cells(i, A) = "Rollup" And Cells(i, B) = "Red" Then
Cells(i, c) = "Red"

ElseIf Cells(i, A) = "Rollup" And Cells(i, B) = "Overdue" Then
Cells(i, c) = "Overdue"

ElseIf Cells(i, A) = " " And Cells(i, B) = " " Then
Cells(i, c) = " "

Else

End If

i = i + 1

Loop


A = A + 4

B = A + 1

c = A + 2

Loop


End Sub
最初,我的代码有应用程序定义的运行时错误或对象定义的错误,但所有If和ElseIf语句都返回了正确的值。在将我的代码更改为用户推荐的代码(请参见此处)后,单元格值始终会自动更改,即使我输入了不同的值

例如,当我在单元格N2列Sales中输入Rollup,然后在单元格O2列Production中输入Green时,单元格P2列Day应根据ElseIf Sales_cell=Rollup和Production_cell=Green返回绿色,然后在Day_cell=Green返回绿色。然而,当我在填充电池O2生产后按Enter键时,电池N2销售自动变为绿色。然后在那之后,我将单元格N2改回Rollup,宏开始工作


有人知道发生了什么事吗?非常感谢你!非常感谢您的帮助

这不是您问题的解决方案

我还没有查看您的方法返回的结果,但我建议您重构代码,使其更具可读性

你也许可以自己发现这个问题

废弃所有If..ElseIf…Else语句,并用更易于阅读且速度更快的Select语句替换它们

Option Explicit

Private Const Green As String = "Green"
Private Const Rollup As String = "Rollup"
Private Const Yellow As String = "Yellow"

Sub Something()

    Dim A As Long, B As Long, C As Long, i As Long

    Select Case True
        Case Cells(i, A) = Green  And Cells(i, B) = Rollup: Cells(i, C) = Green
        Case Cells(i, A) = Rollup And Cells(i, B) = Rollup: Cells(i, C) = Rollup
        Case Cells(i, A) = Rollup And Cells(i, B) = Green:  Cells(i, C) = Green

        'Add more cases here...

    End Select

End Sub

祝你好运。

旁注:也许可以把你的问题浓缩成一个简单的问题,特别强调最小的问题。另外,如果你缩进代码,使结构更易于扫描,人们更可能会提供帮助。这也会让你的生活更轻松。你的代码是在假设目标是一个单元格的基础上运行的——这种情况可能并不总是这样,所以你应该筛选出多单元格的目标范围,这样它们就不会触发你的代码,或者弄清楚你的代码应该如何处理它们并进行适当的更改。
Private Sub Worksheet_Change(ByVal Target As Range)

    Call Module1.single_change(Target)

End Sub
Option Explicit

Private Const Green As String = "Green"
Private Const Rollup As String = "Rollup"
Private Const Yellow As String = "Yellow"

Sub Something()

    Dim A As Long, B As Long, C As Long, i As Long

    Select Case True
        Case Cells(i, A) = Green  And Cells(i, B) = Rollup: Cells(i, C) = Green
        Case Cells(i, A) = Rollup And Cells(i, B) = Rollup: Cells(i, C) = Rollup
        Case Cells(i, A) = Rollup And Cells(i, B) = Green:  Cells(i, C) = Green

        'Add more cases here...

    End Select

End Sub