Andrew Strathclyde
Andrew Strathclyde

Reputation: 337

vba VarType to distinguish between String and Integer

I am preparing a function in VBA to create a query to search a database. One of the parameters, "Value", can be a string (e.g.: "ON") or a number (e.g.: 123), if it's a string, I have to select values different from it (e.g.: "OFF") and if it's a number, I have to select values larger than it (e.g.: 234).

I have prepared the function summarised below, passing the value to compare "valueParam" as a Variant, then trying to detect if "valueParam" is a String or an Integer. The problem is that the function VarType treat each time "valueParam" as a String.

Function prepareQuery(ByVal valueParam As Variant) as String
    Dim STR_Query as String
    STR_Query = "Select * FROM tablename"

    If VarType(valueParam) = vbInteger Then
        STR_Query = STR_Query & " WHERE Value>" & valueParam
    ElseIf VarType(valueParam) = vbString Then
        STR_Query = STR_Query & " WHERE Value<>'" & valueParam & "'"
    End If

    prepareQuery = STR_Query
End Function

Has anyone an idea of why VarType does not recognise the Integer or has another idea to distinguish between numbers and strings?

Thank you very much

Upvotes: 0

Views: 2040

Answers (1)

Jacob
Jacob

Reputation: 43219

You are probably entering the number in a String. Use IsNumeric to transform it beforehand or change your function call.

If IsNumeric(valueParam) Then
  valueParam = CLng(valueParam) 'or CDbl, depending on what you want ...
End If

Upvotes: 2

Related Questions