Excel 2010 Data Validation allow specific layout

女生的网名这么多〃 提交于 2021-02-11 14:49:14

问题


I want to apply data validation to reference numbers, to force the following layout (ideally uppercase only):

XX_NNX-XX_NNN_NN-XXX

X = Numbers

N = Letters

Ex: 12_AB1-23_ABC_AB-123

The following custom formula allows all of it except for numbers - is there any workaround for this?

I don't want to use * since it allows for more characters than I want.

=COUNTIF(A1,"??_???-??_???_??-???")


回答1:


You can choose AND to add a condition to the function you have already written. e.g. following shall test the positions which shall be numeric.

=AND(COUNTIF(A1,"??_???-??_???_??-???"),ISNUMBER((LEFT(A1,2)&MID(A1,6,1)&MID(A1,8,2)&RIGHT(A1,3))+0))

Notes: This is fairly basic approach and may need some tweaks if you have cases involving usage of decimals etc.

Edit: You can try below approach for checking upper case text in specified positions.

=AND(COUNTIF(A1,"??_???-??_???_??-???"),ISNUMBER((LEFT(A1,2)&MID(A1,6,1)&MID(A1,8,2)&RIGHT(A1,3))+0),INDEX(FREQUENCY(-CODE(MID(MID(A1,4,2)&MID(A1,11,3)&MID(A1,15,2),ROW($A$1:$A$7),1)),{-91,-65,0}),2)=7)

Edit2: This turned out to be tougher than I had imagined. Following formula works in DV for cell A1.

=AND(COUNTIF(A1,"??_???-??_???_??-???"),ISNUMBER((LEFT(A1,2)&MID(A1,6,1)&MID(A1,8,2)&RIGHT(A1,3))+0),MIN(FLOOR(CODE(MID(MID(A1,4,2)&MID(A1,11,3)&MID(A1,15,2),ROW($A$1:$A$7),1)),65))=65,MAX(CEILING(CODE(MID(MID(A1,4,2)&MID(A1,11,3)&MID(A1,15,2),ROW($A$1:$A$7),1)),90))=90)

But due to some quirk, Excel won't let me simply paste it. So I wrote a small code for the same which applies DV to cell A1 and surprisingly it accepts that same long formula through code. Make sure that you delete DV in the cell before you run this code.

With Range("A1")
    .Value = "12_AB1-23_ADC_AZ-123"
    .Validation.Add xlValidateCustom, , , "=AND(COUNTIF(A1,""??_???-??_???_??-???""),ISNUMBER((LEFT(A1,2)&MID(A1,6,1)&MID(A1,8,2)&RIGHT(A1,3))+0),MIN(FLOOR(CODE(MID(MID(A1,4,2)&MID(A1,11,3)&MID(A1,15,2),ROW($A$1:$A$7),1)),65))=65,MAX(CEILING(CODE(MID(MID(A1,4,2)&MID(A1,11,3)&MID(A1,15,2),ROW($A$1:$A$7),1)),90))=90)"
End With

Once in there, you can get it in any other cell by simply doing copy >> Paste Special >> Validation.

For clarity, I use Excel 2016.



来源:https://stackoverflow.com/questions/60797748/excel-2010-data-validation-allow-specific-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!