决策宏-基于三列进行决策

时间:2018-07-25 12:50:34

标签: excel vba

我正在尝试编写一个应遵循的宏:

  1. 查看A列,查找以“ SAP”开头的内容(例如:SAP-23F)
  2. 如果不是SAP。-> D列中的空白单元格;如果是->检查B和C列
  3. 检查B和C列->如果在其中找到以“ Kal”开头的任何内容(例如Kal c.2),则将其写入D列“ Kal”,如果没有,则输入“ Obr”

我从一个非常简单的示例开始进行培训,但是即使这个示例也不起作用。我的示例正在查看第1列,如果有A,则应查看第2列,如果没有,则将否定答案写入第3列。如果在第2列中为B或C,则它将答案写入第3列中。见下文:

Sub Test()
    score1 = ActiveSheet.Range("S3:S6").Value
    If score1 = A Then
        Call Test1
    Else
        result = "C"
    End If
    ActiveSheet.Range("U3:U6").Value = result
End Sub

Sub Test1()
    score2 = ActiveSheet.Range("T3:T6").Value
    If score2 = B Then
        result = "X"
    Else
        result = "Y"
    End If
    ActiveSheet.Range("U3:U6").Value = result
End Sub

我的问题是我的示例中有什么问题,以及如何使其适应本文开头提到的实际情况。

感谢您的所有帮助。

3 个答案:

答案 0 :(得分:0)

检查此代码是否对您有帮助。 它基本上使用“ Sheet1”表完成了您所描述的操作,并且表上没有任何标题:

Sub SAPKalObr()

    With Sheets("Sheet1")
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'Finds the last used row at column 1
        For r = 1 To LastRow 'Iterate between every used row at the first column
            If .Cells(r, 1) Like "SAP*" Then 'Testing for starting with SAP on the first column
                If .Cells(r, 2) Like "Kal*" Or .Cells(r, 3) Like "Kal*" Then 'SAP? Testing for Kal on the second or third column
                    .Cells(r, 4).Value = "Kal" 'Returning Kal
                Else
                    .Cells(r, 4).Value = "Obr" 'No Kal? Returning Obr
                End If
            Else
                .Cells(r, 4).Value = " " 'No SAP? Returning blank
            End If
        Next
    End With

End Sub

答案 1 :(得分:0)

一种“公式”方法:

Sub Main()
    With Range("A1", Cells(Rows.Count, 1).End(xlUp)).Offset(,3)
        .FormulaR1C1= "=IF(LEFT(RC1,3)=""SAP"",IF(OR(LEFT(RC2,3)=""Kal"",LEFT(RC3,3)=""Kal""),""Kal"",""Obr""),"""")" 
        .Value = .Value
   End With 
End Sub

答案 2 :(得分:0)

[已解决] :mrexcel.com/forum/excel-questions/1064325-decision-macro.html

非常感谢您的所有帮助!

Sub MyTest()

    Dim lr As Long
    Dim r As Long

    Application.ScreenUpdating = False

'   Find last row with data in column A
    lr = Cells(Rows.Count, "A").End(xlUp).Row

'   Loop through all rows in column A starting with row 2
    For r = 2 To lr
'       Check to see if column A does not start with "SAP"
        If Left(Cells(r, "A"), 3) <> "SAP" Then
            Cells(r, "D") = ""
        Else
'           Check to see if columns B or C start with "Kal"
            If (Left(Cells(r, "B"), 3) = "Kal") Or (Left(Cells(r, "c"), 3) = "Kal") Then
                Cells(r, "D") = "Kal"
            Else
                Cells(r, "D") = "Obr"
            End If
        End If
    Next r

    Application.ScreenUpdating = True

End Sub