"Run-time error 5" when you use Mid(), Left(), or Right() function


For a Microsoft Word 97 version of this article, see 181102 .

For a Microsoft Word 98 version of this article, see 181103 .

For a Microsoft Word 2000 version of this article, see 201979 .

Symptoms


In Microsoft Visual Basic for Applications (VBA), when you use the Mid(), Right(), or Left() function, you may receive the following error message:

Run-time error '5': "Invalid procedure call or argument"

Cause


This behavior occurs when the length argument for the statement is negative.

The Mid() function returns a portion of a text string starting at a given character position. The syntax for the command is as follows

Mid(<string>, <start> [, <length>])
where <string> is the text string to search, <start> is the character position from which to start, and <length> is the number of characters to return. If no <length> argument is specified, or if there are fewer than <length> characters in the text, the function returns all the characters from the <start> position to the end of the string.

Resolution


Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

290140 How to run the sample code for the Office XP programs from Knowledge Base articles

To resolve this issue, be sure to test the length of the string, as in the following example:

Sub ErrorDoesNotOccur()

Dim Test As String
Dim ReturnText As String

' Empty string, could be passed as an empty dialog
' variable, for example.
Test = ""

' Test the length of the string to ensure
' that subtracting 1 from the length leaves
' at least 1 character.
If Len(Test) - 1 > 0 then
ReturnText = Mid(Test, Len(Test) - 1)
End If

End Sub