Excel 强制特定文本vba
有没有办法强制用户只使用单元格中的特定文本? 例如,我希望用户可以只使用以下单词或符号在单元格A1中写入文本: “价格”、“系数”、“加法器”、“主”、“加号”、“加号”、“-”、“(“,”)” 这样用户就可以编写如下内容: ((主价格)+加法器) 但是没有包含与上面不同的字母、单词或符号的文本Excel 强制特定文本vba,excel,vba,text,Excel,Vba,Text,有没有办法强制用户只使用单元格中的特定文本? 例如,我希望用户可以只使用以下单词或符号在单元格A1中写入文本: “价格”、“系数”、“加法器”、“主”、“加号”、“加号”、“-”、“(“,”)” 这样用户就可以编写如下内容: ((主价格)+加法器) 但是没有包含与上面不同的字母、单词或符号的文本 Private Sub Worksheet_Change(ByVal Target As Range) Dim str As String Dim arr(), item ar
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
试试这个
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建议,您可以将
数据验证
与替换
功能结合使用。请将可接受值列表置于范围E1:E8
中。然后在单元格B1
中粘贴此函数=LEN(TRIM(替换)(替换)(替换(替换)(替换(替换)(替换(替换(替换)(替换(替换)(A1,$E$1,“,$E$2,”,$E$3,”,$E$4,”,$E$5,”,$E$6,“,$E$7,”,$E$8)”)
)
在单元格A1
创建数据验证
,将允许设置为自定义
,并在公式选项卡
中输入此公式=B1=0
现在,如果您在单元格A1
中输入错误,数据验证将不允许您输入值
根据@Formard Ed建议,您可以将
数据验证
与替换
功能结合使用。请将可接受值列表置于范围E1:E8
中。然后在单元格B1
中粘贴此函数=LEN(TRIM(替换)(替换)(替换(替换)(替换(替换)(替换(替换(替换)(替换(替换)(A1,$E$1,“,$E$2,”,$E$3,”,$E$4,”,$E$5,”,$E$6,“,$E$7,”,$E$8)”)
)
在单元格A1
创建数据验证
,将允许设置为自定义
,并在公式选项卡
中输入此公式=B1=0
现在,如果您在单元格A1
中输入错误,数据验证将不允许您输入值
您可以将“确定”列表中的所有内容替换为“”。然后检查单元格中文本的长度。如果大于0,则您还剩下一些其他字符。提示:你需要先从最长的事情开始替换。您可能还需要执行“清理/修剪”功能,以消除潜在的空格。您可以将“确定”列表中的所有内容替换为“”。然后检查单元格中文本的长度。如果大于0,则您还剩下一些其他字符。提示:你需要先从最长的事情开始替换。您可能还需要执行clean/trim函数来消除可能存在的空格。为什么不在数据验证中使用公式
=yourformula=0
,并避免使用helper列。现在再试一次,它就可以工作了,一定忘记了=0部分:)我会在那里对任何空格进行修剪:=LEN(trim(…
为什么不在数据验证中使用公式=yourformula=0
并避免使用helper列。现在再试一次,它正在工作,一定忘记了=0部分:)我会在那里对任何空格进行修剪:=LEN(修剪(…