强制特定的文本vba
有什么办法强制用户只使用单元格中的特定文本? 例如,我想用户只能使用以下单词或符号在单元格A1中写入文本:“价格”,“因子”,“加法器”,“主要”,“+”,“ – ”,“ (“,”)“,以便用户可以写下如下内容:((Main-Price)+ Adder),但不包含任何与上述字母,单词或符号不同的文字
尝试这个
Private Sub Worksheet_Change(ByVal Target As Range) Dim str As String Dim arr(), item arr = Array("Price", "Factor", "Adder", "Main", "+", "-", "(", ")") 'text allowed str = Target.Value If Not Application.Intersect(Target, Range("A1")) Is Nothing Then 'change A1 to your range For Each item In arr 'replace all item in arr with "" str = Replace(str, item, "") Next item If Len(Trim(str)) > 0 Then MsgBox "Enter Correct Data", vbCritical, "Invalid Entry" Application.EnableEvents = False Target.Value = vbNullString 'if incorrect data entered make cell empty Application.EnableEvents = True End If End If End Sub
根据@Formard Ed的build议,可以将data validation
与substitute
函数结合使用。 请把您的可接受的值列表在范围E1:E8
。 然后在单元格B1
粘贴这个函数=LEN(TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,$E$1,""),$E$2,""),$E$3,""),$E$4,""),$E$5,""),$E$6,""),$E$7,""),$E$8,"")))
。
在A1
单元格中创builddata validation
,设置允许custom
,并在formula tab
input该公式=B1=0
现在,如果在单元格A1
input错误的input,数据validation将不会让您input值。