I am making a simple UDF that checks if a given country is a member of the OECD. I have two inputs:
Excel cell containing the name of the country
Input containing the first cell of a column containing all the OECD countries.
The function compares the content of the cell Candidate
and of the column of countries
via a loop. If the candidate name does not match with any of the OECD countries, in the end the function classifies it as a non-OECD country.
My code is like this:
Function OECD(Candidate, Countries)
Dim Candidate As String
Dim Countries As String
OECDCountry = Countries 'Variable that changes at every iteration, I compare the name of the candidate to this
For i = 1 To 34
If Candidate.Value = OECDCountry Then
OECD = 2
Else: OECDCountry = Countries.Offset(i, 0)
Next i
'If the column next to the candidate name, where I am running this function, is still empty, record the country as non-OECD
If Candidate.Offset(0, 1) <> 2 Then OECD = 1
End Function
However, when I try to use the function, I receive the following error message while selecting the second input:
The name that you entered is not valid. Reasons for this can include:
-The name does not begin with a letter or an underscore
-The name contains a space or other invalid characters
-The name conflicts with an Excel built-in name or the name of another object in the workbook
Why do I receive this error message and how can I fix it?
Candidate
andCountries
to be passed to your function as arguments, and then you declare variables with identical names in the function itself. Those can't be identical names, which is probably causing part of your issue. You then also try to useCandidate.Value
when you tried toDim Candidate As String
and String variables don't have a .Value property (though the passed argument could if it was passed as a cell reference). – tigeravatar Jan 25 '17 at 17:28Countries As Range
, will make your UDF code a lot simpler – Shai Rado Jan 25 '17 at 17:43OECDCountry
to be aString
. And you will need to declare your UDF as beingVolatile
so that a change to the column listing all the countries will allow your UDF to be reinvoked. And have you considered usingVLOOKUP
to do everything without the need for a UDF? – YowE3K Jan 25 '17 at 17:53