简体   繁体   English

根据另一个单元验证单元输入

[英]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 . 当我在单元格中输入某些文本时,例如在单元格B2- test ,我希望在单元格A6中输入以此字符串开头并以_VAR1结尾(例如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. 我找到了一个简单的公式公式- =IF(A2="test","test_VAR1")但我想将其作为VBA代码。

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: LCase(Range("B2"))还将考虑“ Test”和“ TeSt”:

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): 并且,如果您要检查工作表的每个事件,请将您的代码放在相应的工作表中(下图上的Sheet1,Sheet2和Sheet3):

在此处输入图片说明

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) 我知道您在您的问题中说过您想要宏,但是我不会发布自己的宏(因为我觉得@Vityata的答案应该足够了)

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 如果您只是想在输入中添加关键字“ _VAR1” ,请改用以下公式
    =LTRIM(B2) & "_VAR1"

  2. If the input can be anything, that contains the word "test" 如果输入可以是任何内容,则包含单词“ 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" 您可以使用其他一些变体/技巧,但是这些是您可以用作“构建模块”的一些最基本的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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