有没有更简单/更快的方法来做到这一点?

时间:2018-11-01 17:54:23

标签: vba excel-vba

For Each c In LookupRange

    Cells(c.Row, 15).Activate
    Selectedcell = ActiveCell

    If InStr(Selectedcell, "PLATE") > 0 Then
        Cells(c.Row, 18).FormulaR1C1 = "PP07"
    End If

    If InStr(Selectedcell, "PIPE") > 0 Then
        Cells(c.Row, 18).FormulaR1C1 = "PP10"
    End If

    If InStr(Selectedcell, "NUT") > 0 Then
        Cells(c.Row, 18).FormulaR1C1 = "PP02"
    End If

    If InStr(Selectedcell, "STUD") > 0 Then
        Cells(c.Row, 18).FormulaR1C1 = "PP02"
    End If

    If InStr(Selectedcell, "BOLT") > 0 Then
        Cells(c.Row, 18).FormulaR1C1 = "PP02"
    End If

    'ELSE IF
    'Cells(c.Row, 18).FormulaR1C1 = "PP07"

Next c


Cells(9, 2).Activate

2 个答案:

答案 0 :(得分:1)

例如:

Sub Tester()

    Dim c As Range, txt, res, LookupRange As Range

    Set LookupRange = Range("B7:B16") 'or whatever

    For Each c In LookupRange.Cells

        txt = c.Value
        res = ""
        Select Case True
            Case txt Like "*NUT*", txt Like "*STUD*", txt Like "*BOLT*"
                res = "PP02"
            Case txt Like "*PLATE*"
                res = "PP07"
            Case txt Like "*PIPE*"
                res = "PP10"
            Case Else
                res = "PP07"
        End Select

        c.EntireRow.Cells(18).Value = res
    Next c

End Sub

尽管您发布的代码尚不清楚各种情况是否互斥。

答案 1 :(得分:0)

我只是继续进行您的设置,因此可以使代码最少化一点:

使用Elseif:

Option Explicit

Sub UseElseIf()

Dim LookupRange As Range
Dim c As Variant
Dim Selectedcell As Variant

Set LookupRange = Range("R1:R25")

For Each c In LookupRange
    Cells(c.Row, 15).Activate
    Selectedcell = ActiveCell
    If InStr(Selectedcell, "PLATE") > 0 Then
        Cells(c.Row, 18).FormulaR1C1 = "PP07"
    ElseIf InStr(Selectedcell, "PIPE") > 0 Then
        Cells(c.Row, 18).FormulaR1C1 = "PP10"
    ElseIf InStr(Selectedcell, "NUT") > 0 Then
        Cells(c.Row, 18).FormulaR1C1 = "PP02"
    ElseIf InStr(Selectedcell, "STUD") > 0 Then
        Cells(c.Row, 18).FormulaR1C1 = "PP02"
    ElseIf InStr(Selectedcell, "BOLT") > 0 Then
        Cells(c.Row, 18).FormulaR1C1 = "PP02"
    End If
    'ELSE IF
    'Cells(c.Row, 18).FormulaR1C1 = "PP07"
Next c

Cells(9, 2).Activate

End Sub

在这种情况下,我认为最有效的方法应该是使用CASE运算符。

Sub UseCase()

Dim LookupRange As Range
Dim c As Variant
Dim Selectedcell As Variant

Set LookupRange = Range("R1:R25")

For Each c In LookupRange
Selectedcell = Cells(c.Row, 15).Value
    Select Case Selectedcell
    Case "PLATE"
        Cells(c.Row, 18).FormulaR1C1 = "PP07"
    Case "PIPE"
        Cells(c.Row, 18).FormulaR1C1 = "PP10"
    Case "NUT"
        Cells(c.Row, 18).FormulaR1C1 = "PP02"
    Case "STUD"
        Cells(c.Row, 18).FormulaR1C1 = "PP02"
    Case "BOLT"
        Cells(c.Row, 18).FormulaR1C1 = "PP02"
    End Select
    'ELSE IF
    'Cells(c.Row, 18).FormulaR1C1 = "PP07"
Next c

Cells(9, 2).Activate

End Sub

如果我们重新编写/重新组织代码,当然还有更有效的方法来减少代码。