Home » excel » invalid procedure call for an excel vba built-in function

invalid procedure call for an excel vba built-in function

Posted by: admin May 14, 2020 Leave a comment

Questions:

The following code throws the exception Runtime Error 5: Invalid Procedure Call when the value of the data found in dataSheet.range.value is Null

temp = Right(Trim(dataSheet.range("A" & i).value), Len(Trim(dataSheet.range("A" & i).value)) - 1)

So I fixed it with this:

If dataSheet.range("A" & i).value <> "" Then
        temp = Right(Trim(dataSheet.range("A" & i).value), Len(Trim(dataSheet.range("A" & i).value)) - 1)
    Else
        Exit For
    End If

My question is adding that If statement a valid fix? It seems like something bigger might be going on that’s escaping my grasp…Like shouldn’t the Right() function just return nothing when the String is NULL?

How to&Answers:

An empty cell is not null.

The problem lies in your formula: if a cell is empty or only contains spaces, Len(Trim(dataSheet.range("A" & i).value)) is 0 and Len(Trim(dataSheet.range("A" & i).value)) - 1 is -1. When you run Right(someString, -1) you get an error.

You should do this (it also takes care of cells that only contain spaces):

If Len(Trim(dataSheet.range("A" & i).value)) > 0 Then
    temp = Right(Trim(dataSheet.range("A" & i).value), Len(Trim(dataSheet.range("A" & i).value)) - 1)
Else
    ...
End If