简体   繁体   中英

Validating Cell Input Based on Another Cell

When I input some text in a cell, for example in cell B2- test , I want in cell A6 the input to begin with this string and to end with _VAR1 -for example test_VAR1 .

I have found a simple solution as formula - =IF(A2="test","test_VAR1") but I want to make it as a VBA code.

So any idea how this can be done?

This is the most minimal example that I can come up with. The LCase(Range("B2")) would also take "Test" and "TeSt" into account:

Option Explicit

Public Sub TestMe()

    With ActiveSheet
        If LCase(.Range("B2")) = "test" Then
            .Range("A6") = .Range("B2") & "_VAR1"
        End If 
    End With

End Sub

And if you want to check every event of the worksheet, put your code in the corresponding worksheet (Sheet1, Sheet2 and Sheet3 on the picture below):

在此处输入图片说明

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target.Cells.Count > 1 Then Exit Sub
    If Intersect(Target, Me.Range("B2")) Is Nothing Then Exit Sub

    Application.EnableEvents = False

    If LCase(Target) = "test" Then
        Me.Range("A6") = Target & "_VAR1"
    End If

    Application.EnableEvents = True

End Sub

I know you said in your question you wanted macro, but I'm not going to post my own (because I feel like @Vityata's answer should be sufficient)

However, I got impression from your post, that you could adjust / improve your formula instead and avoid macro altogether. It's usually better to avoid macro, when possible, for compatibility reasons (a lot of users have macros disabled by default)

  1. If you simply want to add the keyword "_VAR1" to the input , use the following formula instead
    =LTRIM(B2) & "_VAR1"

  2. If the input can be anything, that contains the word "test"
    =IF(ISNUMBER(SEARCH("test", TRIM(LOWER(B2)))), LTRIM(B2) & "_VAR1", "Incorrect Input")

  3. The text contains only the word "test" and nothing else
    =IF(TRIM(LOWER(B2))="test", LTRIM(B2) & "_VAR1", "Incorrect input"

There are some other variations / tricks you could do with this, but these are some of the most basic examples you can use as your "building blocks"

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