Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

"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 .

↑ Back to the top


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"

↑ Back to the top


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.

↑ Back to the top


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

↑ Back to the top


Keywords: kboffice12yes, kbfreshness2006, kbdtacode, kberrmsg, kbmacroexample, kbprb, kbword10ready, offrtmpublic, wordrtmpublic, kbbillprodsweep, kb

↑ Back to the top

Article Info
Article ID : 290969
Revision : 1
Created on : 1/7/2017
Published on : 8/15/2007
Exists online : False
Views : 123