WD: ErrMsg Using Mid$(), Left$() or Right$() Function

ID: Q110164

The information in this article applies to:

SYMPTOMS

When you use the Mid$(), Right$() or Left$() function, you may receive the following error message:

   WordBasic error #24 "Bad parameter"

CAUSE

WARNING: ANY USE BY YOU OF THE CODE PROVIDED IN THIS ARTICLE IS AT YOUR OWN RISK. Microsoft provides this macro code 'as is' without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.

This problem occurs when the count or length parameter for the statement is negative.

NOTE: In Word 2.0 for Windows, a negative value in the count parameter of the Mid$(), Right$() or Left$() functions is ignored and does not generate an error.

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

   Mid$(<source$>, <start> [, <count>])

where <source$> is the text string, <start> is the character position from which to start, and <count> is the number of characters to return. If no <count> parameter is specified, or if there are fewer than <count> characters in the text, the function returns all the characters from the <start> position to the end of the string.

The following sample macro illustrates the error message described in the "Symptoms" section of this article:

   Sub MAIN
      ReturnText$ = Mid$("hello", 1, -1)
      MsgBox ReturnText$
   End Sub

The following sample macro returns the error because the length of Test$ minus one is a negative number (0 - 1 = -1):

   Sub MAIN
      Test$ = ""
      Rem Empty string, could be passed as an empty dialog variable for
      Rem example.
      ReturnText$ = Right$(Test$, Len(Test$) - 1)
   End Sub

NOTE: Word version 2.0 for Windows ignores a -1 value for the <count> parameter. So in Word 2.0 all the characters from the first character position to the end of the string are displayed in the message box. In the first example, the string "hello" is displayed.

RESOLUTION

To keep this error from ocurring, first test the length of the string.

For example:

   Sub Main
      ' 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

REFERENCES

Word Developer's Kit, version 6.0, page 594 Word Developer's Kit, Third Edition, page 660

Additional query words:

Keywords          : kberrmsg kbmacro winword macword word7 word95 
Version           : WINDOWS:6.0,6.0a,6.0c,7.0,7.0a
Platform          : WINDOWS
Issue type        : kbprb

Last Reviewed: February 14, 1999