Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA data validation with user defined function

Tags:

excel

vba

I have a user defined function that i want to use in a custom data validation. My function is working properly but when i use it in data validation, it's every time in error...

There is the code:

Public Function AlphaNumeric(pValue) As Boolean
    Dim LPos As Integer
    Dim LChar As String
    Dim LValid_Values As String

    'Start at first character in value
    LPos = 1

    'Test each character in value
    While LPos <= Len(pValue)
        'Single character in value
        LChar = Mid(pValue, LPos, 1)

        'If character is not alphanumeric, return FALSE
        If InStr(REFALPHACHAR, LChar) = 0 Then
           AlphaNumeric = False
           Exit Function
        End If

        'Increment counter
        LPos = LPos + 1
   Wend

   'Value is alphanumeric, return TRUE
   AlphaNumeric = True
End Function

And the setting of my data validation:

Data validation setting

like image 610
ebelair Avatar asked Apr 07 '16 08:04

ebelair


1 Answers

You cannot use a UDF directly in data validation. You can however use it via a named formula.

Select A1, then in Name Manager define a name called IsAlphaNum whose refersto is:

=alphanumeric(A1)

(Note: no $ signs in the cell reference)

Then in your data validation use =IsAlphaNum and uncheck the 'Ignorer si vide' option.

like image 53
Rory Avatar answered Nov 12 '22 11:11

Rory