简体   繁体   中英

VBA Macro help need for Excel

Hello I hope this will make sense,

I have found this script that if a letter or number is in one cell it will input a value in the another cell

I was wondering how I could add multiple rules to this.At the moment if C or 9 is entered in a cell then it produces the sentence "word here will show up"

I want it to show up in a different cell not the adjacent one, and also I want to be able to add different letter to the list to output different values.

EG

Cell Has This in Column A Output when Macro runs in Column E

C or 9 "Word0"

HELLO OR GOODBYE "Word1"

Pink or Yellow "Word2"

Etc, Any help would be great and appreciated as I am very new to VB and Macros.

The code below only does C or 9 I thought I could just add .Forumula to the code below to add more words but it didn't work

Sub CheckValues()
    Application.ScreenUpdating = False
    With Range("A2", Range("A" & Rows.Count).End(xlUp)).Offset(, 1)
        .Formula = "=IF(MIN(FIND({""C"",9},A2&""C9""))<=LEN(A2),""Word0"","""")"
        .Value = .Value
    End With
    Application.ScreenUpdating = True
End Sub

If you're going for a VBA approach then there's no real need to use .Formula . VBA has a Select Case construct that lets you evaluate an expression and carry out a bunch of options based on the outcome of the expression.

Try this:

Sub CheckValues()

    Application.ScreenUpdating = False

    Dim startRow As Integer
    startRow = 2
    Dim endRow As Integer
    endRow = Range("A2").End(xlDown).row

    Dim row As Integer
    Dim word As String

    For row = startRow To endRow

        Select Case Split(Cells(row, 1).Value, " ")(0)

            Case "C", "9"
                word = "Word0"
            Case "HELLO", "GOODBYE"
                word = "Word1"
            Case "Pink", "Yellow"
                word = "Word2"
            Case Else
                word = ""

        End Select

        Cells(row, 5).Value = word

    Next row

    Application.ScreenUpdating = True

End Sub

As you add more options for column a, you only need to repeat the Case *expression* pattern.

Or you could just amend your existing formula and do it without loops:

Sub SO()

With Range("B2:B" & Cells(Rows.Count, 2).End(xlUp).Row).Offset(, 3)
    .FormulaR1C1 = "=IFERROR(""Word""&ROUNDDOWN((MATCH(LEFT(RC[-3],SEARCH("" "",RC[-3])-1),{""C"",""9"",""HELLO"",""GOODBYE"",""Pink"",""Yellow""},0)/2)-0.1,0),"""")"
    .Value = .Value
End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM